Properties
Learn to control access to class fields using properties.
We'll cover the following...
In C#, there are regular and special methods that control access to class
fields. These methods are called properties.
Define a property
Properties are created with the following syntax:
// Like other members, properties can have acess modifiers
[access modifiers] property_type property_name
{
get
{
// Get block contains actions to perform when returning the value of the field
}
set
{
// Set block contains actions to perform when setting the value of the field
}
}
Properties don’t hold any value. They only act as intermediaries between the external code and the fields.
Let’s look at an example.
Press + to interact
Program.cs
Car.cs
using System;namespace Properties{class Program{static void Main(string[] args){Car car = new Car();car.Model = "Lexus LS 460 L";car.Price = 65000;Console.Write($"{car.Model} costs {car.Price} dollars");}}}
Here, the Car
class
defines the private
model
and price
fields that store the model and the price of the car. Along with these fields, there are two public
properties called Model
and ...