Search code examples
c#propertiesinitialization

assigning a Value in Set accssor Instead of using value keyword


I am wondering why this code works fine and comiler doesnt generate any errors or warnings?

class Program
{
    static int _value;
    static int MyValue
    {
        get { return _value; }
        set { _value = 5; }
    }


    static void Main()
    {
        Console.WriteLine(Program.MyValue); //This line print 0 (defoult value of int variables)and its normal 
        Program.MyValue = 10; //after calling the Set accssor we will see that
        Console.WriteLine(Program.MyValue); //The result is 5
        Console.ReadLine();
    }

is this any usefull or special thing? or could it be a technic in Property initialization? thanks in advance.

EDIT: It seems what we have here is a Readonly Property with defoult value am I right?


Solution

  • The set-accessor is nothing other than a method with a parameter, the "value"-parameter. It's up to the method what it does and what it does not.

    void Set__MyValue(int value){
      _value=5;
    }