When i initialize an object using the new object initializers in C# I cannot use one of the properties within the class to perform a further action and I do not know why.
My example code:
Person person = new Person { Name = "David", Age = "29" };
Within the Person Class, x will equal 0 (default):
public Person()
{
int x = Age; // x remains 0 - edit age should be Age. This was a typo
}
However person.Age does equal 29. I am sure this is normal, but I would like to understand why.
The properties get set for Name and Age after the constructor 'public Person()' has finished running.
Person person = new Person { Name = "David", Age = "29" };
is equivalent to
Person tempPerson = new Person()
tempPerson.Name = "David";
tempPerson.Age = "29";
Person person = tempPerson;
So, in the constructor Age won't have become 29 yet.
(tempPerson is a unique variable name you don't see in your code that won't clash with other Person instances constructed in this way. tempPerson is necessary to avoid multi-threading issues; its use ensures that the new object doesn't become available to any other thread until after the constructor has been executed and after all of the properties have been initialized.)
If you want to be able to manipulate the Age property in the constructor, then I suggest you create a constructor that takes the age as an argument:
public Person(string name, int age)
{
Name = name;
Age = age;
// Now do something with Age
int x = Age;
// ...
}
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