user4702921
user4702921

Reputation:

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

Upvotes: 0

Views: 72

Answers (5)

Lukas Kabrt
Lukas Kabrt

Reputation: 5489

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.

Upvotes: 0

if use new keyword , you created new instance your class And all object recreated.

For Example ;

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

            W.Num = 10;

            Example W1 = new Example();

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

this is only information your answer ; you returning different variable. you not set them.

Upvotes: 0

Leigh Shepperson
Leigh Shepperson

Reputation: 1053

num in your Example class is redundant.

If you wrote this before automatic property initialisers were added to c#, it would look like this:

private int num;

 public int Num 
 { 
    get{ return num;}
    set{ num = value;}
}

Writing public public int Num { get; set; } is essentially the same thing behind the scenes. There is no need to implement getNum() (like Java), since this is equivalent to int a = w.Num;.

Upvotes: 0

Dao Tuan Anh
Dao Tuan Anh

Reputation: 21

This is nothing abnormal here.

When you call

Example W = new Example();

then initially num = 0 and Num = 0;

you assigned Num, not num.

Upvotes: 0

Jéf Bueno
Jéf Bueno

Reputation: 434

Because you are returning num, not Num. And num was not initialized, so this value is 0.

Upvotes: 1

Related Questions