anthonytimmers
anthonytimmers

Reputation: 268

What's happening when you use properties without a private field

I was trying to help my friend to understand things such as fields and properties, and getters/setters. He then used properties without a private field, and told me it worked. I never even knew this was possible and can't seem to find too much about it online.

As an example:

public int Number { get; set; }

Instead of:

private int number;
public int Number
{
   get { return number; }
   set { number = value; }
}

It seems to work (as far I can see), but now I have the following questions:

EDIT:

I always thought { get; set; } was the same as get { return x; } set { x = value; }. Oh well, good that I now know it. The question however remains the same. Is one considered better than the other? Pros/Cons?

Upvotes: 0

Views: 100

Answers (1)

Servy
Servy

Reputation: 203802

In the first case the compiler is automatically creating a private field as the backing store for the property, giving it a name not accessible in user code, and creating methods to get and set its value.

In you're code you're taking the time to do it explicitly, and also creating a valid identifier in the scope of the class for that backing field, unlike the previous example.

Upvotes: 1

Related Questions