top of page

C# Tutorial For Beginners: Properties (Get and Set)

Updated: Aug 22, 2021

Private variables can only be accessed within the same class. However, there are different scenarios where we need to access them and this is where properties are used. Property has two methods called ‘get’ and a ‘set’:


class Vehicle

{

private string carcolor;//field


public string CarColor //property

{

get { return carcolor; } // get method

set { carcolor = value; } // set method

}

}


class Program

{

static void Main(string[] args)

{

Vehicle Vehicle_1 = new Vehicle();

Vehicle_1.CarColor = "Blue";

}

}


The CarColor property is associated with the carcolor field (it usually the preferred practice to define bot field/ property with the same name distinguished by uppercase first letter).



2 views0 comments
bottom of page