简体   繁体   中英

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

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.

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

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#?

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM