Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Console.Write in object initializer?

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())
            };
like image 931
saleh kazemian Avatar asked Feb 08 '23 02:02

saleh kazemian


1 Answers

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())
            };
like image 180
Hamid Pourjam Avatar answered Feb 09 '23 17:02

Hamid Pourjam