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())
};
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())
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With