Gautam Jain
Gautam Jain

Reputation: 6849

Property with and without { get; set; }

I am new to C#

What is the difference between

public string MyValue;

and

public string MyValue { get; set; }

I always assumed that both were same. Something was not working in my code. Using the latter form made it work. But don't know what is the difference. Can you help?

Thanks

Upvotes: 32

Views: 22477

Answers (6)

Peter L
Peter L

Reputation: 3343

Needed for Data Annotations
For ASP.NET 3.1, use automatically implemented public property for models that use Data Annotations like [Required].

I learned the hard way that a public field won't work. ModelState.IsValid will always return true.

Upvotes: 0

John Gietzen
John Gietzen

Reputation: 49534

Those are actually very different constructs.

This form is the only way to actually allocate memory for data:

string MyData;

This is called a "field".

This form is called an "automatically implemented property":

string MyData { get; set; }

The compiler translates this onto something like this:

string myDataField;

string MyData
{
    get { return myDataField; }
    set { myDataField = value; }
}

So as you can see they are very different, yet they both end up creating a field for storage. However, using the property allows for much more future flexibility.

Upvotes: 8

Oded
Oded

Reputation: 498904

The first is a public field, the second an automatically implemented public property.

They are not the same. With the auto implemented property the compiler will generate a private backing field.

Though both can work as a way to expose data from your class, you should be using properties following the principle of information hiding - fields should be private and only accessed through properties. This allows you to make changes to the implementation without breaking the callers.

Upvotes: 27

Marc Gravell
Marc Gravell

Reputation: 1062492

If the "latter made it work", you are probably using data-binding; data-binding usually works only against properties (not fields). These can be explicit properties, or automatically implemented properties like in your example.

Note that changing from a field to a property can break serialization if you are using BinaryFormatter (which IMO is deeply flawed anyway), but properties are very much preferred over fields. Absolutely make this change ;p

Upvotes: 12

Jon
Jon

Reputation: 437326

The first one is a field, not a property. Have a look at this question:

What is the difference between a Field and a Property in C#?

Upvotes: 4

Related Questions