top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Explain Anonymous type in C#?

0 votes
251 views
Explain Anonymous type in C#?
posted Apr 17, 2017 by Amit Sharma

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Introduction

Anonymous types allow us to create new type without defining them. This is way to defining read only properties into a single object without having to define type explicitly. Here Type is generating by the compiler and it is accessible only for the current block of code. The type of properties is also inferred by the compiler.

We can create anonymous types by using “new” keyword together with the object initializer.

Example

var anonymousData = new
                    {
                        ForeName = "Jignesh",
                        SurName = "Trivedi"
                    };
Console.WriteLine("First Name : " + anonymousData.ForeName);

Anonymous Types with LINQ Example

Anonymous types are also used with the "Select" clause of LINQ query expression to return subset of properties.

Example

If Any object collection having properties called FirstName , LastName, DOB etc. and you want only FirstName and LastName after the Querying the data then.

class MyData
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DOB { get; set; }
    public string MiddleName { get; set; }
}
static void Main(string[] args)
{
// Create Dummy Data to fill Collection.
    List<MyData> data = new List<MyData>();
    data.Add(new MyData { FirstName = "Jignesh", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1990, 12, 30) });
    data.Add(new MyData { FirstName = "Tejas", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1995, 11, 6) });
    data.Add(new MyData { FirstName = "Rakesh", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1993, 10, 8) });
    data.Add(new MyData { FirstName = "Amit", LastName = "Vyas", MiddleName = "P", DOB = new DateTime(1983, 6, 15) });
    data.Add(new MyData { FirstName = "Yash", LastName = "Pandiya", MiddleName = "K", DOB = new DateTime(1988, 7, 20) });
}  
var anonymousData = from pl in data
                        select new { pl.FirstName, pl.LastName };
    foreach (var m in anonymousData)
    {
        Console.WriteLine("Name : " + m.FirstName + " " + m.LastName);
    }
}

enter image description here

Anonymous type is class type which is directly derived from “System.Object” and it cannot be cast any type other than the object. The Compiler generates a name for each anonymous type. If two or more anonymous type objects are define in the same assembly and the sequence of properties are same in terms of names and types than the compiler treats as same object instances of type. It cannot be declared fields, events, or the return type of a method which having anonymous type. Same as it cannot be declared formal parameter of method, property, constructor or indexer which having anonymous type.

Anonymous type VS Dynamic Type

NET framework 4.0 introduced new keyword called "Dynamic". Object of type dynamic bypasses the static type checking at time of compilation whereas for anonymous type, creating static type and checking type at compile time.
Anonymous type is a class type that contain one or more read only properties whereas dynamic can be any type it may be any type integer, string, object or class.
Anonymous types are assigned type by the compiler.
Anonymous type is directly derived from System.Object whereas Dynamic is differ from object type and DLR (dynamic Language Runtime) define and assign type runtime.
Anonymous types throw compile time errors, Dynamic types does not throw any compile time error but throw run-time errors.
For Anonymous type, Visual studio able to show intellisense because type is known at the time compilation whereas intellisense is not available with dynamic because type is defines at runtime.
Dynamic Type example

dynamic dynamicData = 5;
Console.WriteLine("Data of dynamic type : " + dynamicData);
dynamicData = "Jignesh Trivedi";
Console.WriteLine("Data of dynamic type : " + dynamicData);

enter image description here

Summary
Anonymous types are class type, directly derived from “System.Object” so they are reference type.
If two or more Anonymous types have the same properties in same order in a same assembly then compiler treats it as same type.
All properties of anonymous type are read only.

answer Apr 19, 2017 by Shivaranjini
Similar Questions
+3 votes

What does ? (question mark) after a type name mean in C#?

+1 vote

How to Invoking Delegate? How to pass Delegate as a parameter? Please explain with same code..

...