Can I provide a meaningful name for an anonymous class in C #?

We all know that when we create an anonymous class as follows:

var Employee = new { ID = 5, Name= "Prashant" }; 

... at runtime it will be of type:

 <>f__AnonymousType0<int,string> 

Is there a way to specify a meaningful name for such classes?

+42
c # anonymous-class
Apr 27 '09 at 13:08
source share
10 answers
 public class Employee {} 

+122
Apr 27 '09 at 13:10
source share

This is an anonymous type that defeats the target. These objects are intended for temporary use. Hell, properties are even read-only.

Sorry, I'm a smart ass. The answer is no, there is no way to tell the compiler which name to use for the anonymous type.

In fact, the type names generated by the compiler use illegal characters in their name so that you can not run into names in your application.

+38
Apr 27 '09 at 13:12
source share
 public class Employee { public int ID { get; set; } public string Name { get; set; } } 

Then use the following syntax

 var employee = new Employee { ID = 5, Name = "Prashant" }; 
+36
Apr 27 '09 at 13:12
source share

Make this a regular class with a name?

 public class Employee { public int ID; public string Name; } var Employee = new Employee { ID = 5, Name= "Prashant" }; 
+24
Apr 27 '09 at 13:10
source share

In fact, if you are not afraid to get extremely harsh, you can use TypeBuilder to create your own runtime type based on your anonymous type, which allows you to specify a name for this type. Of course, it is much easier to just declare a class, like almost everyone else in this topic, but the TypeBuilder method is much more interesting.;)

Typebuilder

+23
Apr 27 '09 at 13:26
source share

The answer in Java World will be a local class (defined in the method) that are missing in C #.

+8
Jun 28 '11 at 22:41
source share

Yes, you create an Anonymous class if you want your class to have a name, i.e. Not anonymously , then declare a regular class or structure.

+4
Apr 27 '09 at 13:15
source share

Since this is anonymous, you cannot name it. If you need to know the type name, you must really create a class.

+4
Apr 27 '09 at 13:18
source share

No, there is no way to give a meaningful type name to these classes as you declared them. Anonymous types are just anonymous. It is not possible to explicitly β€œname” a code type without resorting to very ugly hacks.

If you really need to specify a name type, you need to explicitly declare and use the new type with the properties you need.

+4
Apr 27 '09 at 13:20
source share

I think that, by definition, anonymous types cannot have a name, just what its compiler gives. If you are looking for more meaningful development time information for anonymous types, you expect too much from the compiler.

+2
Apr 27 '09 at 13:14
source share



All Articles