4

When I use Console.Write in object initializer I get this error

Error CS0747 Invalid initializer member declarator

person[i] = new Karmand()
            {
                Console.Write("first name:"),
                FirstName = Console.ReadLine(),
                LastName = Console.ReadLine(),
                ID = Convert.ToInt32(Console.ReadLine()),
                Hoghoogh = Convert.ToDouble(Console.ReadLine())
            };
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74

2 Answers2

7

You can't because Console.Write is not an accessible property or field of Karmand. You can only set values of class properties and fields in object initializers.

Your code is a syntactic sugar (a little bit different) for the code below.

var person[i] = new Karmand();
// what do you expect to do with Console.Write here?
person[i].FirstName = Console.ReadLine();
person[i].LastName = Console.ReadLine();
person[i].ID = Convert.ToInt32(Console.ReadLine());
person[i].Hoghoogh = Convert.ToDouble(Console.ReadLine());

You can have a constructor inside Karmand class to print that for you if you want.

public class Karmand
{
    public Karmand(bool printFirstName = false)
    {
        if (printFirstName)
            Console.Write("first name:");
    }

    // rest of class code
}

and then use it like

person[i] = new Karmand(printFirstName: true)
            {
                FirstName = Console.ReadLine(),
                LastName = Console.ReadLine(),
                ID = Convert.ToInt32(Console.ReadLine()),
                Hoghoogh = Convert.ToDouble(Console.ReadLine())
            };
Community
  • 1
  • 1
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
1

Try removing Console.Write("first name:"). Console.Writeline is not an assignment to a property or a field.

From MSDN

An object initializer is used to assign values to properties or fields. Any expression which is not an assignment to a property or field is a compile-time error.

To correct this error Ensure that all expressions in the initializer are assignments to properties or fields of the type.

Update:
If you need to use Console.Writeline, then use it before the object initializer like

Console.Writeline("first name:");
{ person[i] = new Karmand()
            {
                FirstName = Console.ReadLine(),
                LastName = Console.ReadLine(),
                ID = Convert.ToInt32(Console.ReadLine()),
                Hoghoogh = Convert.ToDouble(Console.ReadLine())
            };
Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41