Anonymous Type in C#
We all coders use var keyword while defining new variables in methods and don’t think whether this usage is an anonymous type definition. If the real meaning is not known, it is generally just used because of being shorter than defined type names. This usage is not different rather than classical one as you see below.
var age = 15;
Console.Writeline("Type of age: " + age.GetType().Name);var logSample = new Log();
Console.WriteLine("Type of logSample: " + logSample.GetType().Name);//--Output--
//Type of age: Int32
//Type of logSample: Log// ---------------
// Completely same
// ---------------int age = 15;
Console.WriteLine("Type of age: " + age.GetType().Name);Log logSample = new Log();
Console.WriteLine("Type of logSample: " + logSample.GetType().Name);//--Output--
//Type of age: Int32
//Type of logSample: Log
So, what is the anonymous type and its real usage?
Anonymous Type is a class that is inherited from Object class and named dynamically on runtime. If we need a class structure to use just once in a method scope, we can use Anonymous Type. So we don’t have to create a class to use for once.
It is defined with new keyword without class name.
var log = new { Message = "Error occured.", Time = DateTime.Now };
The properties of this instance are read only and can’t be changed.
Can we pass this variable into a method as parameter?
Yes! But…
Parameter type must have been dynamic. While using dynamic type, we have to be more careful. Because if we use a property that is not contained in dynamic type, it does not give an error in compile time but throws exception in runtime.
So be careful!
static void Main(string[] args)
{
var log = new { Message = "Error occured.", Time = DateTime.Now };
WriteLog(log);
}public static void WriteLog(dynamic log)
{
Console.WriteLine("ErrorMessage: " + log.Message);
Console.WriteLine("Type of log: " + log.GetType().Name);
}//--Output--
//ErrorMessage: Error occured.
//Type of log: <>f__AnonymousType0`2
Can we return an anonymous typed variable from a method?
Yes! The key point is dynamic type again. If we want to return an anonymous typed variable from method, the return type must have been dynamic. Second version of the code is below.
static void Main(string[] args)
{
var log = GetLog();
WriteLog(log);
}public static void WriteLog(dynamic log)
{
Console.WriteLine("ErrorMessage: " + log.Message);
Console.WriteLine("Type of log: " + log.GetType().Name);
}public static dynamic GetLog()
{
var log = new { Message = "Error occured.", Time = DateTime.Now };
return log;
}//--Output--
//ErrorMessage: Error occured.
//Type of log: <>f__AnonymousType0`2
Summary
Anonymous Type;
- can be defined in just a method scope.
- is a class that inherited from Object class.
- is named on runtime.
- can be passed into a method as dynamic parameter.
- can be returned from a method as dynamic.