We all know that when we create an anonymous class like this:
var Employee = new { ID = 5, Name= \"Prashant\" };
...at run time it will be of t
Make it a regular class with a name?
public class Employee
{
public int ID;
public string Name;
}
var Employee = new Employee { ID = 5, Name= "Prashant" };
It's an anonymous type, that defeats the purpose. Those objects are designed to be temporary. Hell, the properties are even read-only.
Sorry, I'm being a smart-ass. The answer is no, there is no way to tell the compiler what name to use for an anonymous type.
In fact, the names of the types generated by the compiler use illegal characters in their naming so that you cannot have a name collision in your application.
Since it's anonymous, you cannot name it. If you need to know the name of a type, then you must really create a class.
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" };
Actually, if you're not afraid of getting extremely nitty gritty, you could use TypeBuilder to build your own runtime type based on your anonymous type, which will allow you to specify a name for the type. Of course, it is much easier to just declare a class as almost everyone else in this thread suggested, but the TypeBuilder way is far more exciting. ;)
TypeBuilder
public class Employee {}