How to Work with Properties and Indexers in C#

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

In the C# programming language, properties and indexers are two key concepts. Properties allow developers to create variables that can be accessed and modified like any other variable, but with the added benefit of being able to control how they are accessed and modified. Indexers provide a way to access elements of a collection by index, just like arrays.

This programming tutorial talks about properties and indexers in C# with relevant code examples to explain the concepts discussed.

Looking to learn C# coding in an online course or classroom environment? We have a list of the Best Online Courses to Learn C# to help get you started.

What are Properties in C#?

A property is similar to a virtual field because it has to get and set accessors and serves as an interface for class members. You can use them to obtain and assign values to and from class members. The get accessor of a property belonging to a class does not take any arguments. Instead, it returns the value of the member of the class with which it is associated. There is an implicit argument named value in the set accessor.

In a class, you can have both static or instance members. Similarly, a class can have static or non-static properties. The get accessor of a class is used to return the value of the member of the class it represents.

The set accessor assigns a value to the class member it represents.

What are Indexers in C#?

The C# programming language provides excellent support for indexers, a feature that allows programmers to use an object much like an array. Indexers, sometimes known as smart arrays, may be defined in the same way that properties are.

An indexer indexes instances of a class or struct in the same way that arrays are indexed. Typically, an indexer is used when your class represents a collection of items. Using an indexer, you may then access a particular element using index.

Indexers are a powerful way to organize code, improve readability and maintainability, and improve performance. Indexers can provide a predetermined order for the items in a collection. This is especially helpful when the collection has large dimensions. You can take advantage of indexers to simplify the retrieval of data by providing an identifier for the item that needs to be retrieved.

How to Program Properties in C#

The following code example illustrates the syntax for declaring a property in C#:

{
  get
  {
  }
  set
  {
  }
}

Note that the access modifier of a property can be public, private, protected, or internal. The return type of a property in C# can be any valid C# type.

Consider the following class named Customer:

public class Customer
    {
        public int CustomerID
        {
            get; set;
        }
        public string FirstName
        {
            get; set;
        }
        public string LastName
        {
            get; set;
        }
        public string Address
        {
            get; set;
        }
    }

Developers can use the following C# code example to create an instance of the Customer class and assign values to each of its properties:

Customer customer = new Customer();
customer.CustomerID = 1;
customer.FirstName = "Joydip";
customer.LastName = "Kanjilal";
customer.Address = "Hyderabad, India";

Read: Top 10 Security Testing Tools for Developers

How to Program Indexers in C#

The following code snippet illustrates the syntax for declaring an indexer in C#:

  this[arguments]
{
  get
  {
  }
  Set
  {
  }
}

Similar to property, the access modifier of an indexer can be public, private, protected, or internal.

Consider the following class named Product:

internal class Product
    {
        private string[] productName = new string[25];
        public string this[int index]
        {
            get
            {
                return productName[index];
            }
            set
            {
                productName[index] = value;
            }
        }
    }

Programmers can use the following code snippet to assign values using the indexer and then display them in the console window:

Product product = new Product();
product[0] = "Lenovo Laptop";
product[1] = "DELL Laptop";
product[2] = "Acer Laptop";
product[3] = "HP Laptop";
product[4] = "Asus Laptop";
for (int i = 0; i < 4; i++)
    Console.WriteLine(product[i]);
Console.ReadLine();

When you execute the program, the output will be similar to the image below:

C# Indexer and Properties tutorial

Coders can also declare a generic indexer class as shown in the C# code example given below:

    internal class CustomCollection
    {
        private T[] array = new T[25];
        public T this[int i]
        {
            get { return array[i]; }
            set { array[i] = value; }
        }
    }

Support for Inheritance and Polymorphism in C# Indexers

In C#, indexers can be extended, can be abstract, and also polymorphic. The code listing below shows how programmers can declare a base indexer class and then extend it in C#:

internal class ProductBase
    {
        protected string[] productName = new string[25];
        public virtual string this[int index]
        {
            get
            {
                return productName[index];
            }
            set
            {
                productName[index] = value;
            }
        }
    }
    internal class Product: ProductBase
    {
        public override string this[int index]
        {
            get
            {
                return productName[index];
            }
            set
            {
                productName[index] = value;
            }
        }
    }

The code snippet below illustrates how you can declare an abstract base indexer class in C#:

public abstract class AbstractProductBase
    {
        protected string[] productName = new string[25];
        public abstract string this[int index]
        {
            get; set;
        }
    }

Final Thoughts on C# Properties and Indexers

Both properties and indexers have been a part of the C# programming language for a long time. Indexers are like properties but that are accessed using index. While properties can be both static and non-static, indexers are always the instance members of a class.

Hence, indexers of a class can never be static. All indexes accept this as a parameter. Note that this is a pointer or a reference that points to the current object.

Read more C# programming tutorials and software development how-tos.

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