-2

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 ?

  • It's not the `Console.WriteLine` that is doing anything special. You are misunderstanding what `ABC.Roll = -1` actually does. – Mark Feb 05 '16 at 15:24

2 Answers2

1

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.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

An assignment has a return value (the assigned value). So even though you're not storing the -1 it's still the return value of the assignment itself.

This would print 0:

ABC.Roll = -1;
Console.WriteLine(ABC.Roll); 
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
Mark
  • 1,360
  • 1
  • 8
  • 14
  • lol i know that.... it will give me the output 0 as my business logics is value > 0 and compiler have set by default 0 for int valuetypes – Muhammad Ahsen Haider Feb 05 '16 at 15:03
  • Your question is why it prints `-1` when you were expecting `0` in your example and I'm telling you why: Because you were writing the return value of the assignment instead of the property and I'm showing you the difference. – Mark Feb 05 '16 at 15:10