c# - About Encapsulation : properties -
case :
class example { private int roll; public int roll { { return roll; } set{ if (value > 0) { roll = value; } } } //public example() //{ // roll = 500; //} } class practice_4 { static void main(string[] args) { example abc = new example(); console.writeline(abc.roll = -1); console.readline(); } }
output : -1
i have set business logic not contain illegal value , gives me default value "0"..
case ii:
class example { private byte roll; public byte roll { { return roll; } set{ if (value > 0) { roll = value; } } } //public example() //{ // roll = 500; //} } class practice_4 { static void main(string[] args) { example abc = new example(); console.writeline(abc.roll = -1); console.readline(); } }
above code displaying compile time error change valuetype int byte
error: constant value -1 cannot converted byte ...
what console.writeline method ?
it's because assigment expression returns value being assigned -1
in case. doesn't return abc.roll
, can verify outputting property value after assignment:
console.writeline(abc.roll = -1); //-1 console.writeline(abc.roll); //0
so abc.roll
never changes cause of validation logic in setter
method.
Comments
Post a Comment