The property is like a field, but the only difference is it can contain a logic. The property in C# contains get & set blocks which can contain login in it. For example, let’s create a class Library.cs and add two public properties BooId and BooName as shown below.
public class Library
{
int iBookId;
string sBooName;
public int BookId
{
get { return iBookId; }
set { iBookId = value; }
}
public string BookName
{
get { return sBooName; }
set { sBooName = value; }
}
}
As shown above, each property declared with get and set blocks with some code. Even we can call methods also within get and set blocks of properties.
Automatic Properties
Properties can also declare without any logic in get and set blocks as shown below and these are called automatic properties.
public class Library
{
public int BookId
{
get; set;
}
public string BookName
{
get; set;
}
}
Automatic properties are very useful when we do not require any logic in get, set blocks. We can access the properties by creating an object for the class. Open Microsoft Visual Studio 2015 and create some console application, add Library class given above. Now create an object for Library class and access BookId & BookName properties as below.
class Program
{
static void Main(string[] args)
{
Library obj = new Library();
obj.BookId = 100;
obj.BookName = "C# 6.0 Programming";
Console.WriteLine("Book Id: " + obj.BookId);
Console.WriteLine("Book Name: " + obj.BookName);
Console.ReadLine();
}
}
We can make particular property as read-only by just containing get block as shown below.
public class Library
{
int iBookId;
string sBooName;
public int BookId
{
get { return iBookId; }
}
public string BookName
{
get { return sBooName; }
set { sBooName = value; }
}
}
Here we made the BookId property as read—only by removing set block. That means we can set the value for BookId, only we can get the value.
Property Initializers in C# 6.0
Before C# 6.0, we cannot set the default value for automatic properties. From C# 6.0 onwards, we can initialize the value of the property during declaration itself like below.
public class Library
{
public int BookId { get; } = 100;
public string BookName { get; set; } = "Microsoft C# 6.0 Programming";
}
As shown here, we can initialize the values for properties. Important thing here is we can initialize the value for read-only properties also (like we set the value for BookId property above).
Expression Bodied properties in C# 6.0
In C# 6.0, we can declare the read-only properties as Lambda expressions like below.
public class Library
{
int iTotalBooks = 100;
int iBookPrice = 20;
public int TotalBooksValue => iTotalBooks * iBookPrice;
}
Here we created the
TotalBooksValue read-only property using Lambda expression.