These two are certainly not equivalent.
public string FirstName;
public string FirstName { get; set; }
The first is a typical field, just like a plain-old C++ class
member.
The second is a property. More specifically it is an auto-implemented property. Properties are essentially just syntactic sugar for _get()
and _set(value)
functions, like one would be used to in Java. Auto-implemented properties take it a step further and hide the backing field where the data is saved for you.
Since you're supposed to use properties, and not fields, for your public API, many .NET frameworks/APIs like MVC, EF, etc. will do special things with the properties of a class (for example automatically create a database schema).
Why are you supposed to use properties? Consider the following example. You have a plain-jane class, with an auto-implemented property.
public class Foo {
public int Bar { get; set; }
}
And you have some client code:
var f = Foo();
f.Bar = 32;
Let's say you want to add an event that fires when you change something in Foo
. Since you used a property, you can simply change the implementation:
public class Foo {
private int m_bar;
public int Bar {
get { return m_bar; }
set {
m_bar = value;
OnChanged();
}
}
public event EventHandler Changed;
protected virtual void OnChanged() {
var evt = Changed;
if (evt != null)
evt(this, EventArgs.Empty);
}
}
and (the important part!) the client-facing API stays the same. This is just one example of how properties are definitely the "right choice".