In Encapsulation get is readonly where set is write only
Why my output is 11110 when not using special member function?
code:
class practice_4
{
static void Main(string[] args)
{
example ABC = new example();
// ABC.Roll_ = 11;
Console.WriteLine(ABC.Roll_ );
Console.ReadLine();
}
}
class example
{
private int roll = 11110;
public int Roll_
{
get
{
return roll ;
}
//set{
// if (value > 10)
// { roll = value; }
// else
// { Console.WriteLine("error"); }
//}
}
//public example()
//{
// roll = 110;
//}
}
Output :
11110
but when I use special member function : public example()
class practice_4
{
static void Main(string[] args)
{
example ABC = new example();
Console.WriteLine(ABC.Roll_ );
Console.ReadLine();
}
}
class example
{
private int roll = 11110;
public int Roll_
{
get
{
return roll ;
}
}
public example()
{
roll = 110;
}
}
so It display Output:
110
and discard 11110
To Answer your question "Why my output is 11110 when not using special member function?"
The special member function in your class is the Constructor of your class, which means this is the special function that initializes/constructs your object from your class definition, rule to remember here is, constructors are called after your private variables statements and also when the constructor is finished the construction is finished, which means your class's internal state(variables) are now assigned(among other things).
However if you initialize the private variables like you are in private int roll = 11110;
line, this line executes before the constructor is called. but as you are overwriting the value of roll in constructor, the value of your private variable gets overwritten.