C# Tutorials
C# Methods
C# Classes
C# Examples
Before we can begin to define structures, you must have a basic understanding of "Encapsulation".
Encapsulation definition is, to ensure that "sensitive" data is hidden from users. To do this, you must:
You learned in the preceding chapter that a private variables can only be accessed in the same class (the external class cannot access it). However, sometimes we need access to them - and it can be done through properties.
Property is similar to a combination of variable and method, and has two methods: get method and set method:
class Person
{
private string name; // field
public string Name // property
{
get { return name; } // get method
set { name = value; } // set method
}
}
Name property is associated with a name field. It is good practice to use the same name in both the property and the private field, but with the first capital letter.
The get method returns the value of the variable name.
The set method assigns a value for the name. The value keyword represents the value we give the property.
We can now use the Name feature 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);
}
}
C# also provides a way to use short / default layouts, where you do not have to define a field field, and you should only write get; and set; inside the property.
The following example will show 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);
}
}