I have this small class looking like this:
private static int field1 = - 1;
private static int field2 = field1 + 1;
public static void Sum()
{
field1 = 10;
Debug.WriteLine(field2);
}
A call to Sum() writes ‘0’. Why?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Those aren’t properties – they’re fields.
field2is only related tofield1at initialization time – after that, they’re completely independent fields. It’s not like thefield1 + 1expression is re-evaluated every timefield2is read or every timefield1is written.If you want
field2to just depend on the value offield1, you should make it a property: