Search code examples
c#encapsulationconsole.writeline

About Encapsulation : properties


Case I :

class example
{
   private int roll;
   public int Roll
   {
       get { 
           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 a business logic that does not contain any illegal value and gives me by default value "0"..

Case II:

class example
{
   private byte roll;
   public byte Roll
   {
       get { 
           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 is displaying compile time error as I just change valuetype Int to byte

error: constant value -1 cannot converted to byte ...

what Console.WriteLine Method really do ?


Solution

  • It's because assigment expression returns the value that is being assigned which is -1 in this case. it doesn't return the ABC.Roll, you can verify that by outputting the property value after the assignment:

    Console.WriteLine(ABC.Roll = -1); //-1
    Console.WriteLine(ABC.Roll); //0
    

    So the ABC.Roll actually never changes cause of the validation logic in setter method.