namespace tutor4
{
class Class1
{
int _num = 2;
public int num
{
get
{
return _num;
}
Your setter for num
property is wrong.
It should not be
set
{
_num = num;
}
because in this case it does nothing (sets _num back to its value since getter for num
returns _num
so this line is equivalent to _num = _num
)
It should be
set
{
_num = value;
}
MSDN explanation about value keyword:
The contextual keyword value is used in the set accessor in ordinary property declarations. It is similar to an input parameter on a method. The word value references the value that client code is attempting to assign to the property
Also note: your num
property is just simple wrapper of _num
field of class. If you don't need some complex logic in getter and setter for this property - you can change it to auto-implemented property like this:
class Class1
{
public int num { get; set;}
public Class1
{
num = 2;
}
}
Until C# version 6 you should assign default value to auto-implemented property in class constructor.
In C# version 6 (not yet released, should be available this summer) you will be able to assign default value to auto-implemented property in declaration:
public int num { get; set;} = 2;