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

Asked

Viewed 161 times

3

When I saw the use of 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 of 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 doesn’t seem to be the same thing as object?

What is the relationship of new {} with object in C#?

1 answer

5


As the return message of GetType() show, it’s an anonymous guy (Anonymous type), He’s a guy who doesn’t have a name in his code. Of course, internally it has a name because it’s not possible to have an unnamed guy in the CLR, but your code doesn’t see it and doesn’t care about it. Example.

In C# all types are derived from Object, including this. Object It doesn’t have a structure, it hasn’t been, the anonymous type may have. This one specifically doesn’t make any sense, it has no use because it hasn’t been. Anonymous types are about state.

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

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

Almost always create a Object "concrete" also makes no sense. Object probably shouldn’t even be a class.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.