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.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...