Anonymous Types - CSharp Custom Type

CSharp examples for Custom Type:Anonymous Types

Introduction

An anonymous type is a class created by the compiler to store a set of values.

var dude = new { Name = "Bob", Age = 23 };

You must use the var keyword to reference an anonymous type because it doesn't have a name.

The property name of an anonymous type can be inferred from an expression.

int Age = 23;
var dude = new { Name = "Bob", Age, Age.ToString().Length };

Two anonymous type instances declared within the same assembly will have the same underlying type if their elements are named and typed identically:

Demo Code


using System;//from   w ww  .ja va 2s.  c om
class Test
{
    static void Main()
    {

        var a1 = new { X = 2, Y = 4 };
        var a2 = new { X = 2, Y = 4 };
        Console.WriteLine(a1.GetType() == a2.GetType());   // True
    }
}

Result


Related Tutorials