Properties
Properties are a special type of member variables.
They have getters and setters which allow access from outside.
A property with only a getter can be read from outside but not written to.
A property with only a setter can be written to but cannot be read from outside.
A property with both a getter and a setter can be read and written to from outside.
Essentially, a getter is identical to a method that returns the value of a variable, and a setter is a method that takes in a parameter and writes that value to the variable.
public class Person
{
private int id;
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
static void Main(string[] args)
{
var person = new Person();
person.Id = 1;
person.Name = "Sach";
Console.WriteLine("{0}'s ID is {1}", person.Name, person.Id);
}With C# this syntax can be greatly simplified:
Last updated