What name is given in C # when we use the expression “new {}”?

Posted on

Question :

When I saw the use of the expression new {} I remembered Javascript, where I use new Object and {} are equivalent.

Just for study purposes, I made some comparisons, to see if Csharp followed the same idea as Javascript, but it seems I was wrong:

var obj1 = new {};

var obj2 = new object(){

Console.WriteLine(obj1.GetType()); // <>f__AnonymousType0

Console.WriteLine(obj2.GetType()); // System.Object

In this case, what is the name given to new {} , since it does not seem to be the same as object ?

What is the ratio of new {} to object in C #?


Answer :

Since the GetType() return message shows, it is an anonymous type ( anonymous type ), is a type that has no name in its code. Of course internally has a name because it is not possible to have an unnamed type in the CLR, but your code does not see and does not care about it. Example .

In C # all types are derived from Object , including this. Object does not have a structure, has no state, the anonymous type can have. This specifically does not make any sense, has no utility for not having been. Anonymous types are about state.

In general, this type should be used less often and use more language tuple ( not the library ), but in some cases it is still useful, even for compatibility. Example .

Tuples should only be used when it really is the best mechanism, anonymous types should be used even less.

Almost always creating a concrete “%” of% does not make sense either. Object probably should not even be a class.

For C # to have a semantics similar to JS should use Object , but is discouraged whenever possible. Every language has its own philosophy .


Leave a Reply

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