Compiler Error CS0021
Cannot apply indexing with [] to an expression of type 'type'
An attempt was made to access a value through an indexer on a data type that does not support Indexers.
You may get CS0021 when trying to use an indexer in a C++ assembly. In this case, decorate the C++ class with the DefaultMember
attribute so the C# compiler knows which indexer is the default. The following sample generates CS0021.
The following C++ example compiles to a .dll file. Note that the DefaultMember attribute is commented out in order to generate the error.
// CPP0021.cpp
// compile with: /clr /LD
using namespace System::Reflection;
// Uncomment the following line to resolve
//[DefaultMember("myItem")]
public ref class MyClassMC
{
public:
property int myItem[int]
{
int get(int i){ return 5; }
void set(int i, int value) {}
}
};
The following C# example calls the .dll file. It attempts to access the class via an indexer, but because no member was declared as the default indexer, the error is generated. You can address the error by uncommenting the line [DefaultMember("myItem")]
in the .cpp file in the preceding example.
// CS0021.cs
// compile with: /reference:CPP0021.dll
public class MyClass
{
public static void Main()
{
MyClassMC myMC = new MyClassMC();
int j = myMC[1]; // CS0021
}
}
.NET feedback
.NET is an open source project. Select a link to provide feedback: