Before we dive into Properties, we need to understand the concept of Encapsulation.
Encapsulation is the process of making sure that "sensitive" data is hidden from users. To achieve this, you must:
private.public get and set methods, through a Property, to access and update the value of a private field.A property is like a combination of a variable and a method. It cannot take any parameters, but it provides two special blocks of code called accessors: the get accessor and the set accessor.
get method returns the value of the variable.set method assigns a value to the variable. (The value keyword represents the value we are assigning).using System;class Person { // private field (hidden from the outside) private string name;
// public property (exposed to the outside) public string Name { get { return name; } // returns the private field set { name = value; } // updates the private field } }
class Program { static void Main(string[] args) { Person myObj = new Person(); // The 'set' accessor is called here: myObj.Name = "Liam"; // The 'get' accessor is called here: Console.WriteLine(myObj.Name); } }
Naming Convention: It is standard practice to use a lowercase letter for the private field (
name) and an uppercase letter for the public property (Name).
C# provides a brilliant shortcut! If you don't need any special logic inside your get and set accessors, you can use Automatic Properties.
With automatic properties, you do not even need to define the private field. C# will secretly create one for you behind the scenes.
using System;class Person { // Automatic property! No private field needed. public string Name { get; set; } }
class Program { static void Main(string[] args) { Person myObj = new Person(); myObj.Name = "Liam"; Console.WriteLine(myObj.Name); } }
set accessor, you could add logic to ensure the age is never negative before assigning it.set accessor.Which keyword represents the value being assigned inside a 'set' accessor?