[C#] Properties

Before I started to use C#, I had used Java for a while. It was quite a lot of work to provide getters and setters for each model class. C#’s Property syntax is a nice addition. The syntax is cleaner (Not everybody agrees, though) and sometimes it saves a lot of coding efforts.

 

1. Encapsulation

Main idea of properties (setters and getters) is “Encapsulation“. You do not want to expose your data fields directly outside of the class. Fields should be hidden as “private” and public accessors may be provided.

Also you can enforce business rules in the accessor methods; such as checking the minimum or maximum limit of the field.

 

2. Setters and Getters

The traditional way to provide public accessors is to use a “Getter” method and a “Setter” method.

public class BankAccount
{
  private decimal balance;
  public decimal GetBalance()
  {
    return balance;
  }
  public void SetBalance(decimal balance)
  {
    if (balance > 0M)
      this.balance = balance;
  }
}

 

3. Properties

A property can be understood as a shortcut syntax to accessor methods.

  • Getter method: inside the “get” block
  • Setter method: inside the “set” block
  • Inside the “set” block, the “value” keyword is used to represent an input value
public class BankAccount
{
  private decimal balance;

  public decimal Balance
  {
    get { return balance; }
    set
    {
      if (balance > 0M)
        this.balance = value;
    }
  }
}

When the code is compiled, the compiler creates a getter and a setter method for each property. For example, “get_balance()” and “set_balance()” methods are created for the “Balance” property.

There are some other things you might want to know about properties.

  • You do not need to provide both “get” and “set” properties
  • Read-only Property: the “get” block only
  • Write-only Property: the “set” block only
  • You can override the access modifier in a get or a set block
  • You can define static properties.

 

4. Automatic Properties

If you do not need to provide any validations to properties, it might be tedious to create properties for all field members.

C# provides a shortcut syntax for this situation.

  • Do not define a data field. The compiler creates it for you.
  • Setters and getters might have different access modifiers
  • C#6 provides the new syntax of read-only properties
public class BankAccount
{
  public decimal Balance { get; set; }
  public double InterestRate { get; private set; }
  public DateTime CurrentDate { get; } = DateTime.Now; // C# 6
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s