C# Property Examples

Class Property

Property (Icon copyright Microsoft)

Properties get and set values. The C# language provides them as a convenient way to simplify syntax. They are implemented as methods in the intermediate language. They are standard access points to a class from external code.

Unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the statements to be executed when their values are read or written. Hejlsberg et al., p. 37

Example

Note

First, this program introduces an Example class. One field is present and it is used as a backing store for the Number property. The Number property provides get { } and set { } implementations. The get { } implementation must include a return statement. The set { } implementation receives the implicit argument 'value', which is the value to which the property is assigned.

Value Keyword
Program that uses public int property [C#]

using System;

class Example
{
    int _number;
    public int Number
    {
	get
	{
	    return this._number;
	}
	set
	{
	    this._number = value;
	}
    }
}

class Program
{
    static void Main()
    {
	Example example = new Example();
	example.Number = 5; // set { }
	Console.WriteLine(example.Number); // get { }
    }
}

Output

5
Main method

Instance property. The Number property is an instance property, which means that the enclosing class Example must first be instantiated before it can be used. The Main method instantiates Example and then uses the Number property setter (example.Number = 5) and getter (example.Number).

Example 2

You can use other types in properties, such as enum types. This example shows the DayOfWeek enum type in a property, which is defined in the System namespace. Also, the example demonstrates how you can insert code in the getter (or setter) that checks the backing store or the parameter value.

DayOfWeek Enum
Program that uses enum property [C#]

using System;

class Example
{
    DayOfWeek _day;
    public DayOfWeek Day
    {
	get
	{
	    // We don't allow this to be used on Friday.
	    if (this._day == DayOfWeek.Friday)
	    {
		throw new Exception("Invalid access");
	    }
	    return this._day;
	}
	set
	{
	    this._day = value;
	}
    }
}

class Program
{
    static void Main()
    {
	Example example = new Example();
	example.Day = DayOfWeek.Monday;
	Console.WriteLine(example.Day == DayOfWeek.Monday);
    }
}

Output

True

Example 3

You can also use the private accessibility modifier on your property setter or getter. In this example, we require that the IsFound property only be set in the Example class domain. We set the IsFound property in the Example constructor. Then, we can only get the property in the Program.Main method.

Program that uses private setter in property [C#]

using System;

class Example
{
    public Example()
    {
	// Set the private property.
	this.IsFound = true;
    }
    bool _found;
    public bool IsFound
    {
	get
	{
	    return this._found;
	}
	private set
	{
	    // Can only be called in this class.
	    this._found = value;
	}
    }
}

class Program
{
    static void Main()
    {
	Example example = new Example();
	Console.WriteLine(example.IsFound);
    }
}

Output

True

Example 4

You can also make an entire property private. If you do this, you can only use the property in the same enclosing class. The Display method in the below example shows how you can use the private property.

Program that uses private property [C#]

using System;

class Example
{
    int _id;
    private int Id
    {
	get
	{
	    return this._id;
	}
	set
	{
	    this._id = value;
	}
    }
    public void Display()
    {
	// Access the private property in this method.
	this.Id = 7;
	Console.WriteLine(this.Id);
    }
}

class Program
{
    static void Main()
    {
	Example example = new Example();
	example.Display();
    }
}

Output

7

Example 5

Properties can also be static, which means they are associated with the type and not an instance of the type. Static classes can only have static properties. Also, this Count property has a side effect that causes the field to be incremented upon each access. Side effects are not usually a good design feature in programs.

Static Modifier Static Class Static Property
Program that uses static property with side effect [C#]

using System;

class Example
{
    static int _count;
    public static int Count
    {
	get
	{
	    // Side effect of this property.
	    _count++;
	    return _count;
	}
    }
}

class Program
{
    static void Main()
    {
	Console.WriteLine(Example.Count);
	Console.WriteLine(Example.Count);
	Console.WriteLine(Example.Count);
    }
}

Output

1
2
3

Omitting the setter. Another interesting thing about this program is that the setter is omitted entirely. It is sometimes useful to omit the setter when you have a property that computes a value entirely in memory or based on other fields or properties only.

Example 6

Another great feature in the C# programming language is called the automatically implemented property. This feature indicates to the C# compiler that a hidden field be generated and used as the backing store. Then, the get and set statements are expanded to use that hidden field.

Program that has automatically implemented property [C#]

using System;

class Example
{
    public int Number
    {
	get;
	set;
    }
}

class Program
{
    static void Main()
    {
	Example example = new Example();
	example.Number = 8;
	example.Number *= 4;
	Console.WriteLine(example.Number);
    }
}

Output

32
Programming tip

Using property in expression. Another interesting tip in this example is that you can use a property getter in an expression. The *= operator is used to multiply the property by itself; this is the same as "example.Number = example.Number * 4". Because properties are meant to look like fields, this is allowed; obviously methods are not allowed to do this.

Example 7

With automatically implemented properties, you can specify that the getter or setter be private or restricted to some other accessibility domain. This makes it possible to have a private setter and a public getter, which can improve the information hiding in your object model.

Program with automatically implemented property 2 [C#]

using System;

class Example
{
    public Example()
    {
	// Use private setter in the constructor.
	this.Id = new Random().Next();
    }
    public int Id
    {
	get;
	private set;
    }
}

class Program
{
    static void Main()
    {
	Example example = new Example();
	Console.WriteLine(example.Id);
    }
}

Output

2077325073

Note: You cannot omit either the getter or setter in an automatically implemented property. The error reported by the C# compiler reads: "Automatically implemented properties must define both get and set accessors."

Indexers

This keyword

Indexers are another form of property in the C# language. They use the token 'this' for their name, and also have square brackets with an argument. This member type in the language is covered in another article on this site.

Indexer Examples

Interface property

You can also specify that a property be required by an interface. There is a special syntax for this in the C# programming language. On types that implement the interface, you must provide implementations for the property.

Interface Types

Performance

Performance optimization

The C# compiler and .NET Framework use a lot of advanced optimizations to ensure that properties are very efficient. These same optimizations are used on methods, which share the underlying implementation with properties.

This program benchmarks with Stopwatch and performs the two loops ten times. Each inner loop has 100,000,000 iterations. The property's backing store is a string, as is the field. The performance impact of the static keyword is probably not important here.

Program that benchmarks properties [C#]

using System;
using System.Diagnostics;

class Program
{
    static string _backing; // Backing store for property
    static string Property // Getter and setter
    {
	get
	{
	    return _backing;
	}
	set
	{
	    _backing = value;
	}
    }
    static string Field; // Static field

    static void Main()
    {
	const int m = 100000000;
	for (int x = 0; x < 10; x++) // Ten tests
	{
	    Stopwatch s1 = new Stopwatch();
	    s1.Start();
	    for (int i = 0; i < m; i++) // Test property
	    {
		Property = "string";
		if (Property == "cat")
		{
		}
	    }
	    s1.Stop();
	    Stopwatch s2 = new Stopwatch();
	    s2.Start();
	    for (int i = 0; i < m; i++) // Test field
	    {
		Field = "string";
		if (Field == "cat")
		{
		}
	    }
	    s2.Stop();
	    Console.WriteLine("{0},{1}",
		s1.ElapsedMilliseconds,
		s2.ElapsedMilliseconds);
	}
	Console.Read();
    }
}

Results

Property get/set:  604.6 ms
Field read/assign: 603.6 ms
Note

Results. There was no difference in performance with the property shown and the direct field. I conclude that the property access is inlined completely. There is no need to use manual inlining of properties for performance optimization in regular cases.

Tip: The JIT compiler is smart enough to inline properties that don't have logic inside of them, so that they are as efficient as fields. But there is still MSIL generated for properties—this means the JIT must deal with them, not just the C# language compiler.

Summary

The C# programming language

In this set of examples, we pointed out many ways to use properties in the C# programming language. Properties are a powerful way to replace methods and present a more intuitive way to use your objects. They are a combination of fields and methods on a conceptual level.

.NET