Monday, September 2, 2013

Anonymous Types in C#




n this article, we will learn how to use anonymous types in C#.

  1. Anonymous types were introduced in C# 3.0.
  2. These are data types generated on the fly at runtime.
  3. These data types are generated by the compiler rather than explicit class definition.

Program.cs

using System;
using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace
ConsoleApplication17
{
    class Program
    {
        static void Main(string[] args)
        {
            var MyAnonClass = new
            {
                Name = "Scott",
                Subject  = "ASP.Net"
            };
            Console.WriteLine(MyAnonClass.Name);
            Console.Read();
        }
    }
}

Outputanan1.gif

A class without a name is generated and assigned to an implicitly typed local variable.
How does it work internally?
  1. For anonymous type syntax, the compiler generates a class.
  2. Properties of the class generated by the complier are value and data type given in the declaration.
  3. Intellisense supports anonymous type class properties.

    anan2.gif
  4. Properties of one anonymous type can be used in the declaration of other anonymous types.
anan3.gif

Program.cs
using System;
using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace
ConsoleApplication17
{
    class Program
    {
        static void Main(string[] args)
        {
            var MyAnonClass = new
            {
                Name = "Scott",
                Subject = "ASP.Net"
            };
            Console.WriteLine(MyAnonClass.Name);
            Console.Read();
            var SecondAnoynClass = new
            {
                info = MyAnonClass.Name + MyAnonClass.Subject
            };
            Console.WriteLine(SecondAnoynClass.info);
            Console.Read();
        }
    }
}
Output

anan5.gif

No comments:

Post a Comment