Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is nameof(object) not allowed?

Tags:

c#

c#-6.0

nameof

In C# 6.0 you can write this:

var instance = default(object);
var type = typeof(object);

They have the same result of:

var instance = default(System.Object);
var type = typeof(System.Object);

But you can't write this:

var name = nameof(object);

It generates the following error:

Invalid expression term 'object'.

But you can still write this:

var name = nameof(System.Object);

Why nameof(object) does not compile?

like image 804
Massimiliano Kraus Avatar asked Nov 04 '16 11:11

Massimiliano Kraus


People also ask

What is the purpose of Nameof C#?

C# NameOf operator is used to get name of a variable, class or method. It returns a simple string as a result. In error prone code, it is useful to capture a method name, in which error occurred.

When was Nameof added to C#?

The nameof operator, added in C# 6.0, addresses this — it allows capturing the string names of symbols that are in the scope. In the example below, ReSharper suggests the replacement of the string literal "order" in the argument of the ArgumentNullException() with the nameof(order) .

What is the Nameof?

idiom. : used to indicate the name that is used for someone or something.


1 Answers

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)

like image 82
Jeroen van Langen Avatar answered Oct 14 '22 17:10

Jeroen van Langen