What does this mean ? public Name {get; set;} [duplicate]
I see this quiet often in C# documentation. But what does it do?
public class Car
{
public Name { get; set; }
}
Solution 1:
It is shorthand for:
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
The compiler generates the member variable. This is called an automatic property.
Solution 2:
In simple terms they are referred as property accessors. Their implementation can be explained as below
1.get{ return name} The code block in the get accessor is executed when the property is Read.
2.set{name = value} The code block in the set accessor is executed when the property is Assigned a new value.
Eg.(Assuming you are using C#)
class Person
{
private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
set
{
name = value;
}
}
}
-
Now when you refer to this property as below
Person p = new Person();// Instantiating the class or creating object 'p' of class 'Person'
System.Console.Write(p.Name); //The get accessor is invoked here
The get accessor is invoked to Read the value of property i.e the compiler tries to read the value of string 'name'.
2.When you Assign a value(using an argument) to the 'Name' property as below
Person p = new Person();
p.Name = "Stack" // the set accessor is invoked here
Console.Writeline(p.Name) //invokes the get accessor
Console.ReadKey(); //Holds the output until a key is pressed
The set accessor Assigns the value 'Stack" to the 'Name property i.e 'Stack' is stored in the string 'name'.
Ouput:
Stack
Solution 3:
It's an automatic read-write property. It's a C# 3.0 addition. Something like:
public class Car {
private string name;
public string Name { get { return name; } set { name = value; } }
}
except that you can't directly access the backing field.
Solution 4:
It's called an Auto-Implemented Property and is new to C# 3.0. It's a cleaner syntax when your access to the property doesn't need any special behavior or validation. It's similar in function to:
public class Car
{
private string _name;
public string Name
{
get { return _name; }
set {_name = value; }
}
}
So it saves a fair amount of code, but leaves you the option later to modify the accessor logic if behavior or rules need to change.
Solution 5:
It is the equivilent of doing:
private string _Text;
public string Text
{
get { return _Text; }
set { _Text = value; }
}
Except you don't have access to the private variable while inside the class.