Before we start to explain properties, you should have a basic understanding of "Encapsulation".
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must:
private
public
get
and set
methods, through properties, to access and update the value of a private
fieldYou learned from the previous chapter that private
variables can only be accessed within the same class (an outside class has no access to it). However, sometimes we need to access them - and it can be done with properties.
A property is like a combination of a variable and a method, and it has two methods: a get
and a set
method:
class Person
{
private string name; // field
public string Name // property
{
get { return name; } // get method
set { name = value; } // set method
}
}
The Name
property is associated with the name
field. It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter.
The get
method returns the value of the variable name
.
The set
method assigns a value
to the name
variable. The value
keyword represents the value we assign to the property.
If you don't fully understand it, take a look at the example below.
Now we can use the Name
property to access and update the private
field of the Person
class:
class Person
{
private string name; // field
public string Name // property
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
The output will be:
Liam
C# also provides a way to use short-hand / automatic properties, where you do not have to define the field for the property, and you only have to write get;
and set;
inside the property.
The following example will produce the same result as the example above. The only difference is that there is less code:
Using automatic properties:
class Person
{
public string Name // property
{ get; set; }
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
The output will be:
Liam
get
method), or write-only (if you only use the set
method)截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!