TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Property Examples

These C# examples show properties. A property is a method that gets or sets a value.

Property. On a class, a property gets and sets values.

A simplified syntax form, properties are implemented in the IL as methods.

With properties, we create standard access points from external places. We access Name, not GetName(). This leads to simpler code. It provides data-binding features.

Get, set. We introduce an Example class. One field, an integer, is present. It is used as a backing store for the Number property.

Number: This is an int property. Number provides get { } and set { } implementations.

Get: The get { } implementation must include a return statement. It can access any member on the class.

Set: The set { } implementation receives the implicit argument "value." This is the value to which the property is assigned.

Value

Based on:

.NET 4.5

C# program that uses public int property

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

Enum. This example shows the DayOfWeek enum type in a property. We also insert code in the getter (or setter) that checks the backing store or the parameter value.

EnumDayOfWeek

C# program that uses enum property

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

Private. We make a private property. Here the IsFound property can only be set in the Example class. We set it in the Example constructor.

Then: We can only get the property in the Program.Main method by using an Example instance.

C# program that uses private setter in property

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

Entire property. We can also make an entire property private. If we do this, we can only use the property in the same enclosing class.

Private: The Display method in the example (below) shows how to use the private property.

Note: This syntax is less useful in most programs. But it exists, and may be helpful in a complex class.

Class

C# program that uses private property

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

Static. Properties can also be static. This means they are associated with the type and not an instance. Static classes can only have static properties.

Static PropertyStatic Class

Count: This property (below) has a side effect. It causes the field to be incremented upon each access.

Caution: Side effects are not usually a good design feature in programs. They can make the logic hard to follow.

Setter: This is omitted. This makes sense for a property that computes a value entirely in memory, or based on other fields or properties.

C# program that uses static property

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

Automatic. Next, we see automatically implemented property syntax. A hidden field is generated. Then, the get and set statements are expanded to use that hidden field.

Expression: The *= operator is used to multiply the property by itself. This is the same as "example.Number = example.Number * 4".

Tip: Because properties are meant to look like fields, this is allowed. Obviously methods are not allowed to do this.

C# program that uses automatically implemented property

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

Automatic, private. Let us consider how to make getters or setters on an automatic property. We cannot omit either the getter or setter in this kind of property.

Info: The error reported by the C# compiler reads: "Automatically implemented properties must define both get and set accessors."

C# that uses private setter, auto property

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

Indexers. These are properties. They allow element access (like an array). They use the token "this" for their name, and square brackets with an argument.

Indexer

Tip: Types such as the List (one of my favorites) use indexers to do element accesses. It looks like an array but is not.

Interface. A property can be part of an interface. There is a special syntax for this. On types that implement the interface, we must provide implementations for the property.

Interface

Note: The special syntax required here is a reason to avoid properties in some programs. No one wants to deal with complex syntax rules.

Performance. Compiler optimizations ensure that properties are efficient. These same optimizations are used on methods, which share the underlying implementation with properties.

Methods

Here: This program benchmarks with Stopwatch and performs the two loops ten times. Each inner loop has 100 million iterations.

Result: There was no difference in performance with the property and the direct field. I conclude the property access is inlined.

Tip: The JIT compiler is smart enough to inline properties that don't have logic inside of them. So they are as efficient as fields.

C# that benchmarks properties

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

Research. I researched properties in the C# specification. This is the most important concept: a property is not a storage location like a field.

Instead: A property is just a method. It has special syntax that looks more like a field.

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.

The C# Programming Language

Prop. I like the prop snippet. It is one of my favorites. In Visual Studio, try typing prop and pressing tab twice where you want to put a property.

Then: Change the fields as needed. We get an automatically implemented property.

Snippets

A review. Properties are used throughout programs. They are a powerful way to replace methods. They present a more intuitive way to use objects.

On a conceptual level, properties combine fields and methods. But in terms of implementation, properties are just methods. They are optimized, in the JIT compiler, just like methods.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf