.NET Anonymous Types

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.

Here’s an example of how to implement an Anonymous Type

    1 class Program

    2 {

    3     static void Main()

    4     {

    5         var thing = new { ID = 123, Name = “Frank” };

    6         Console.WriteLine(“ID: {0}, Name: {1}”, thing.ID, thing.Name);

    7         Console.ReadLine();

    8     }

    9 }

Notice how line 5 looks like an Object Initializer without the specification of an existing type. Line 5 simply creates a new “something” – there is no specification of a type. Hence the term, Anonymous Type!


Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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