Anonymous Types in C# (OR) VB .NET Applications

Introduction


Anonymous types as the name suggests,  help us  to create an object without declaring its data type. Since name of the data type is not specified that the type is referred to as an anonymous type.
We have lot of resources around us on this concept, but I still see some confusion and arguments on this concept that made me to write this blog post. I will try to explain it in simple words so that a novice can understand the basics of the concept.


VB.NET
view sourceprint?
1.Emp = New With {
2.         .EmplD = 123,
3.         .FName = "Hima",
4.         .LName = “Vejella” ,
5.         .Country = "India"
6.            }


C#.NET
view sourceprint?
1.var Emp = new {
2.        FirstName = "Hima",
3.        LastName = "Vejella",
4.        DOJ = DateTime.Now,
5.        EMPCode = 150
6.          };
The above code snippet is an anonymous declaration in VB. We can notice that the as key word is not required to declare it.
Visual Studio Editor is user-friendly to give us the IntelliSense as below. Once you declared the type then you can access all the properties.
ananymoustypes
When the above code reaches the complier these are the steps that are done internally.
  1. Compiler automatically generates anonymous class.
  2. It anonymously instantiate an object that contains the properties in anonymous type
  3. The instantiated object is assigned to the anonymous type variable "Emp"
The anonymous type inherits from Object, it holds the properties specified in declaring the object.
If we look at the IL Code and we can examine it and understand in detail as explained
anonymous methods


view sourceprint?

01..class private auto ansi sealed VB$AnonymousType_0`4
02.       extends [mscorlib]System.Object
03.{
04.  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
05.   = ( 01 00 00 00 )
06.  .custom instance void [mscorlib]System.Diagnostics.DebuggerDisplayAttribute::.ctor(string)
07.   = (
08.     01 00 3E 45 6D 70 6C 44 3D 7B 45 6D 70 6C 44 7D   // ..>EmplD={EmplD}
09.     2C 20 46 4E 61 6D 65 3D 7B 46 4E 61 6D 65 7D 2C   // , FName={FName},
10.     20 4C 4E 61 6D 65 3D 7B 4C 4E 61 6D 65 7D 2C 20   //  LName={LName},
11.     43 6F 75 6E 74 72 79 3D 7B 43 6F 75 6E 74 72 79   // Country={Country
12.     7D 00 00
13.    )                                       
14.// }..
15.} // end of class VB$AnonymousType_0`4
The given code-snippet creates a variable called Emp. This Emp is assigned to an instance of anonymous type that has LastName, FirstName and Country as properties.

To Access Anonymous Type


That is very simple as we access non anonymous types.

VB.NET


view sourceprint?
1.MessageBox.Show(Emp.FirstName & " " & Emp.LastName & " " & Emp.Country)

C#.NET


view sourceprint?
1.Console.WriteLine(Emp.FirstName + “Emp.LastName” + ”Emp.DOJ” + “Emp.EmpCode” );
This will give us the necessary output

0 comments:

Post a Comment