Massimiliano Kraus Massimiliano Kraus - 1 month ago 15
C# Question

C#, nameof(object) doesn't compile

Why

nameof(object)
doesn't compile? It seems to work with any other called type or identifier.

For example, a simple method like:

public void Method1()
{
var nameOfObjectType = nameof(object);
}


generates the following error:


Invalid expression term 'object'.


I can't understand why it is valid for
nameof(Object)
, or any other token.

Answer

The difference is that object is a synonym for the class Object and nameof() doesn't work on synonyms.

Same applies to nameof(int) vs nameof(Int32)