patrick patrick - 1 year ago 52
C# Question

You create an object of type ANumber. The class is defined as follows.What is the value of _number after the code is executed?

After creating an instance of

Anumber
using the code below, the value of the private
_number
field is 3, not 7. Can someone explain why this is so?

class Program
{
static void Main()
{
Anumber anumber = new Anumber(3);
}
}

class Anumber
{
private int _number = 7;

public Anumber()
{

}

public Anumber(int num)
{
_number = num;
}
}

Answer Source

Class member fields (like _number) are initialized before the constructor code is executed, so _number will be 7 for a very brief period before the constructor reassigns it's value to 3;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download