Anonymous Types

Anonymous Types are one of the nice feature in .net framework and i have never seen this code snippet anywhere in my project. Anonymous Types enable you to create objects without writing a class definition for the data type. Instead, the compiler generates a class for you. The class has no usable name, inherits directly from Object, and contains the properties you specify in declaring the object. You create anonymous types by using the new operator together with an object initializer

Dim carID As Integer = 100
Dim carName As String = "Car Name"

Dim carValue = New With {Key carID, carName}

'Which is same as

Dim anotherCar = New With {Key .ID = carID, .Name = carName}
Console.WriteLine("CarID : {0}", anotherCar.ID)
Console.WriteLine("Car Name : {0}", anotherCar.Name)

Anonymous types contain one or more public read-only properties.You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type. Similarly, you cannot declare a formal parameter of a method, property, constructor, or indexer as having an anonymous type.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s