An Overview of Properties in C#

C# Tutorials
Properties are an important feature of C# and object oriented programming (OOP) that enables developers to encapsulate and manage the state of an object in a controlled and safe way. They provide a way to read and write the values of fields of a class, and can be used for a variety of purposes, including data validation, computed values, and access control.

This programming tutorial discusses properties in C#, their benefits, and how they can be used in C#.

Before delving too deep into this article, we have a few articles discussing the basics of object-oriented software development if you need a refresher or are new to the concept:

What Are Properties in C#?

In C#, a property is a member of a class that can be used to read or write values from and to a field of the class. Properties are used to encapsulate the implementation details of a class and provide a controlled way to access its internal state.

It is a mechanism for exposing private fields of a class to the outside world while still controlling the access to them. A property provides a way to read and write the value of a private field by using get and set accessors.

Properties are used in C# for a variety of reasons, including to provide encapsulation, validate data, compute values, and to enforce constraints:

  • Encapsulation: By encapsulating the state of an object behind a property, you can prevent direct access to the private fields of the object, which helps maintain the integrity of the object’s state.
  • Data validation: Properties can be used to validate the data being set on an object. For example, you could use a property to ensure that a number is always positive, or that a string has a maximum length.
  • Computed values: Properties can be used to compute a value on the fly based on the values of other properties or fields.
  • Access control: Properties can be used to control access to an object’s state by limiting access to certain fields or properties.
  • Properties can be used to enforce constraints, validate data, and provide a simple way to access data in an object.

You can learn more about encapsulation in our tutorial: Overview of Encapsulation in C#.

Types of Properties in C#

There are several types of properties in C#, including read-only, write-only, indexer, and virtual types:

  • Read-only properties: These properties only have a get accessor, which means that their value cannot be changed once they are set.
  • Write-only properties: These properties only have a set accessor, which means that their value can only be set, not read.
  • Auto-implemented properties: These properties are shorthand for defining a private field and its associated get and set methods.
  • Indexer properties: You can use these properties to access instances of a class using an index, much the same way you do with an array.
  • Virtual properties: Virtual properties are defined in the base class and they can be overridden by the derived classes.
  • Static properties: As the name suggests, static properties are not associated with the object of the class, instead they are associated with the class.
  • Abstract properties: Abstract properties are declared in an abstract class or interface in C#. You must implement them in any non-abstract class that derives the abstract class or implements the interface.

How to Program Properties in C#

In C#, properties are defined using the get and set keywords. The get method is used to retrieve the value of the property, while the set method is used to set the value of the property.

The syntax for defining a property in C# is as follows:

access-modifier type PropertyName
{ 
   get 
   { 
        // Write your get accessor logic here
    } 
   set 
   { 
       // Write your set accessor logic here
   }
}

The following code example illustrates a property in C#:

public class MyClass
{
    private int myProperty;
    public int MyProperty
    {
        get { return myProperty; }
        set { myProperty = value; }
    }
}

In the preceding code example, MyProperty is a property of the MyClass class. It has a private backing field myProperty, which is accessed by the get and set accessors of the property. While a get accessor is used to retrieve the value of a data member of the class, and the set accessor sets a specified value to the data member.

Here is another code example in which the Person class has a property called Name.

Here is another example of a simple property in C#:

 
public class Person
{ 
  private string firstName, lastName, address;
  public string FirstName 
  { 
     get 
     { 
       return firstName; 
     } 
     set 
     {
       firstName = value; 
     } 
   }
public string LastName 
  { 
     get 
     { 
       return lastName; 
     } 
     set 
     {
       lastName = value; 
     } 
   }
public string Address 
  { 
     get 
     { 
       return address; 
     } 
     set 
     {
       address = value; 
     } 
   }
}

In this example, the Person class has three private fields, namely, firstName, lastName, and address.. You can access each of them using the corresponding public properties named FirstName, LastName, and Address.

Properties can also have different access modifiers, such as public, private, protected, or internal, just like other class members. They can also be read-only, write-only, or read-write, depending on whether or not they have a set method.

Read: Best Bug Tracking Software for C# Developers

What is an Automatic Property in C#?

In C#, an automatic property is a shorthand syntax for defining a property that simplifies the syntax for declaring and initializing properties. Using automatic properties, programmers can declare a property without having to define a private field to store the property value explicitly.

Instead, the C# compiler automatically generates a private backing field for you, and you can access the property using get and set accessors. The basic syntax for an automatic property in C# is as follows:

public class MyClass
{ 
  public string MyProperty { get; set; }
}

In this code example, MyProperty is an automatic property. The get and set keywords define the accessors for the property, and the type of the property is string. When you create an instance of the MyClass class and set the value of the MyProperty property, the compiler automatically creates a private backing field to store the value. For example, you can create an instance of MyClass and set the value of MyProperty like this: var myObject = new MyClass();

myObject.MyProperty = "This is a sample text";

In this example, the value ” This is a sample text “ is stored in the private backing field created by the C# compiler for the MyProperty property.

Here is another example of an auto-implemented property in C#:

 
public class Author
{ 
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

In this code example, the “Id”, “FirstName”, and “LastName” properties do not have an explicit field mapped to them, but the compiler generates one for each of them automatically.

Automatic properties can be useful for reducing boilerplate code in your C# classes, but keep in mind that they have some limitations. For example, you cannot add additional logic to the get and set accessors of an automatic property, such as validation or calculations. If you need to do more than simply get or set a property value, you will need to define a traditional property with an explicit private field.

Final Thoughts on C# Properties

Properties are a powerful feature of C# that allow for flexible data access and manipulation, while also enabling developers to enforce constraints and protect your data from being exposed directly. You can take advantage of properties to implement encapsulation, access control, and data validation in object-oriented programming.

Check out our tutorial: Class Members in C# for more information on OOP programming and working with classes.

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read