What is value
keyword here and how is it assigning the value to _num
? I\'m pretty confused, please give the description for the following code.
In the context of a property setter, the value
keyword represents the value being assigned to the property. It's actually an implicit parameter of the set
accessor, as if it was declared like this:
private int _num
public int num
{
get
{
return _num;
}
set(int value)
{
_num=value;
}
}
Property accessors are actually methods equivalent to those:
public int get_num()
{
return _num;
}
public void set_num(int value)
{
_num = value;
}
The value keyword is a contextual keyword, that is, it has a different meaning based on its context.
Inside a set
block, it simply means the value that the programmer has set it to. For instance,
className.num = 5;
In this case, value
would be equal to 5 inside of the set
block. So you could write:
set
{
int temp = value; //temp = 5
if (temp == 5) //true
{
//do stuff
}
_num = value;
}
Outside of a set
block, you can use value
as a variable identifier, as such:
int value = 5;
Note that you cannot do this inside a set
block.
Side note: You should capitalize the property num
to Num
; this is a common convention that makes it easier for someone who's reading your class to identify public and private properties.
Properties
are the way you can READ, WRITE or COMPUTE values of a private field
or class variable
.
The set
or setter
inside a property
is used when the code assigns a value into the private field
or (class) variable
.
The value
keyword means simply "the thing that is being assigned".
public class StaffMember
{
private int ageValue;
public int Age
{
set
{
if ( (value > 0) && (value < 120) )
{ this.ageValue = value; }
}
get {
return this.ageValue;
}
}
}
//Rob Miles - C# Programming Yellow Book