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

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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...