Actually second one is not property it is public field.
Properties in C# is just shortcut for two type of methods - accessors and mutator (or get and set). So, when you write some property like
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
Compiler will actually create two methods
public string get_Name() { return _name; }
public void set_Name(string value) { _name = value; }
When you write
public string Name { get; set; }
then compiler will generate those two methods and generate backing storage (field _name
) for you.
When you do not use get
and set
, then it is simple field (like _name
) and no methods will be generated by compiler.
For your second question:
What is the difference between a field and a property in C#
Because property is actually a method(s), they could be abstract or virtual, could be overridden. Properties could be part of interface. Properties could be used in data binding. You can add any logic to property (e.g. raising some event, lazy-loading, or performing validation). You can define different access level for setting and getting property (e.g. private and public). This all is not true for public fields.