Search code examples
c#automatic-properties

Automatic properties


I want to know that when you create an Automatic property and invoke the set in the main() method for a random value , where is that value being stored ?
as in this example :



    class Program
        {
            static void Main(string[] args)
            {
                Example W = new Example();

                W.Num = 10;
                Console.WriteLine("{0}", W.Num);

                Console.WriteLine("{0}", W.getNum());
            }
        }



    class Example
            {
                private int num;

                public int Num { get; set; }

                public int getNum() { return num; }
            }

why is the output :
10
0


Solution

  • Auto-implemented properties makes code cleaner when no additional logic is required for the getter or setter. The compiler actually generates a backing field for the auto-implemented property, but this backing field is not visible from your code.

    In your example there is no connection between the num field and the Num property, so there no reason why the num should change.