C# Error CS0021 – Cannot apply indexing with [] to an expression of type ‘type’

C# Compiler Error Message

CS0021 – Cannot apply indexing with [] to an expression of type ‘type’

Reason for the Error

You will get this error when you attempt to access a value through an indexer on data types that does-not support indexers in C#.

For example, assume that you have the below code snippet.

public class DeveloperPublish
{
    public static void Main()
    {
        Class1 obj = new Class1();
        int result = obj[1];

    }
    public class Class1
    {

    }
}

When you compile this code in Visual Studio, you’ll receive the below compiler error. The reason being you are trying to access the value from the instance of Class1 which doesn’t support it.

Error CS0021 Cannot apply indexing with [] to an expression of type ‘DeveloperPublish.Class1’

C# Error CS0021 - Cannot apply indexing with [] to an expression of type 'type'

Solution

Ensure that you access the value only via the supported format. Incase you are using a C++ library, you could use the DefaultMember attribute.

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Hey, wait!Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.