• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Friday, December 29, 2017

Anonymous Types in C#

 Abhishek Tomer     December 29, 2017     Anonymous Types, C#, Interview Question     12 comments   

Hi friends! Today we are going to learn about Anonymous Types in C#.

Let's start with the Introduction
Anonymous is a type that doesn't have any name. Anonymous type allows you to create a new type by using the new keyword and object initializer syntax without defining its class. The var is used to hold the reference of anonymous types. The Type of anonymous is generated by the c# compiler that is accessible within the block. All Properties of the anonymous type is read-only.

Example:
var anonymous = new { ID = 1, Name = "Same", Age = 26 };
anonymous.ID = 27;  //this will give a complie time error because all properties of anonymous type are read-only
Description:
Here we can see that we have created a new type with new keyword and object initializer syntax without defining a class and reference of this type hold by var. And we set values of anonymous type properties.

We cannot pass an anonymous object as a parameter to a method because of the scope of its presence within the method or lock. But you can only pass an anonymous object as a parameter to a method that type is dynamic. But it is not recommended.

Example:
var anonymous = new { ID = 1, Name = "Same", Age = 26 };
MyData.GetData(anonymous); //calling method

class MyData
{
        public static void GetData(dynamic d)
        {
            Console.WriteLine(d.Name);
        }
}
Real Use Of Anonymous Type:
The real use of Anonymous Type is in LINQ query select clause where we can define new properties which are not defined in any class.

Example:
List data = new List {
            new MyData { FirstName = "Jignesh", LastName = "Trivedi", MiddleName = "G", DOB =new DateTime(1990, 12, 30) },
            new MyData { FirstName = "Tejas", LastName = "Trivedi", MiddleName = "G", DOB = newDateTime(1995, 11, 6) },
            new MyData { FirstName = "Rakesh", LastName = "Trivedi", MiddleName = "G", DOB = newDateTime(1993, 10, 8) },
            new MyData { FirstName = "Amit", LastName = "Vyas", MiddleName = "P", DOB = newDateTime(1983, 6, 15) },
            new MyData { FirstName = "Yash", LastName = "Pandiya", MiddleName = "K", DOB = newDateTime(1988, 7, 20) }
        };
           

var s = (from p in data
         select new
         {
             Name = p.FirstName + " " + p.MiddleName + " " + p.LastName,
             DateOfBirth = p.DOB
         }).ToList();

class MyData
{
      
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DOB { get; set; }
        public string MiddleName { get; set; }
}
Description:
Here we have to get the list of data and select the Name and DataOfBirth properties which are not defined any class this is an anonymous type property.

Important Points:
  1. Anonymous type object can only be passed as a parameter to a method which has a dynamic data type.
  2. Anonymous type can be defined using the new keyword or object initializer syntax.
  3. var, is used to hold anonymous type references.
  4. Anonymous type is a reference type and all the properties are read-only.
  5. The scope of an anonymous type is local to the method where it is defined.

Anonymous method in C#

  • An anonymous method is a method without a name that allows us to create delegate instances without writing a separate method.
  • We can pass an only input parameter to the anonymous method.
  • With anonymous method delegate parameter is optional.
  • Anonymous method must be assigned to a delegate
  • An anonymous method can access outer variables or functions.
  • An anonymous method can be passed as a parameter that accepts delegate as a parameter.
  • public delegate void Print(int value);
    class Test
    {
        public static void PrintHelperMethod(Print printDel, int val)
        {
            val += 10;
            printDel(val);
        }
        static void Main(string[] args)
        {
            PrintHelperMethod(delegate (int val) { Console.WriteLine("Anonymous method: {0}", val); }, 100);
        }
    }
    
  • An Anonymous method can be used as event handlers.
  • saveButton.Click += delegate(Object o, EventArgs e)
    {
        System.Windows.Forms.MessageBox.Show("Save Successfully!");
    };
    
Without Anonymous Method:
public static class Program
{
    //Step=1 declare delegates
    public delegate int delCustomer(int ID);

    static void Main(string[] args)
    {
        //Step-3 instantiated delegates           
        delCustomer del = new delCustomer(getCustomerName);
       var result= del.Invoke(1);
        Console.WriteLine("Result"+ result);
    }

    //Step-2 create method that pass to delegate
    public static int IsExists(int ID)
    {
       return  ID==1?1:0;
    }
}
Description:
we can see that without anonymous method we need all 3 steps.

With Anonymous Method:
public static class Program
{
    //Step=1 declare delegates
    public delegate int delCustomer(int ID);

    static void Main(string[] args)
    {
        //Step-3 instantiated delegates          
            delCustomer del = delegate (int ID)
            {
                return ID == 1 ? 1 : 0;
            };   
    }
}
Description:
we can see that with an anonymous method we do not need to create a separate method for delegate references.

Anonymous method limitations:
  • It cannot contain jump statement like goto, break or continue.
  • It cannot access ref or out parameter of an outer method.
  • It cannot have or access unsafe code.
  • It cannot be used on the left side of the is operator.
Summary:
So, Guys, this is all about Anonymous Types in C#
I Hope in this post covered all the points about Anonymous Types in C#

Please share this post with your friends and colleagues.
For any queries please post a comment below.

Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

12 comments:

  1. Travel nearbyJune 4, 2018 at 10:54 AM

    cbse 10th & 12th results 2018
    Kerala board 10 results 2018

    ReplyDelete
    Replies
      Reply
  2. Travel nearbyJune 19, 2018 at 4:25 PM

    Yoga Pose & health Benefits
    yoga for meditation
    yoga for weight loss
    yoga for lower back pain
    yoga for beginners
    hatha yoga poses
    bikram yoga poses types
    yoga for inner peace

    ReplyDelete
    Replies
      Reply
  3. Travel nearbyJune 26, 2018 at 10:56 AM


    Voter Id Card
    online check voter id status by name
    online apply Voter Id Card Registration
    Voter Id Correction
    online duplicate Voter Id Card
    online check process voter id 2018-19
    apply for online voter card
    check voter id status by date of birth
    Maharashtra Voter ID Card Registration

    ReplyDelete
    Replies
      Reply
  4. Travel nearbyJuly 30, 2018 at 11:16 AM



    This is a wonderful article, Given so much info in it, You can see Travel Nearby best tourist place Best Honeymoon Destination in this page.Places to visit in Goa
    Weekend Gateways Near Pune

    ReplyDelete
    Replies
      Reply
  5. ModicareAugust 17, 2018 at 9:52 AM

    Greetings! Very useful advice in this particular
    post! It’s the little changes that make the largest changes.

    Modicaren busniness plan how to earn big money in modicare
    Modicare marketing business
    Top-5-network-marketing-companies-in-india

    ReplyDelete
    Replies
      Reply
  6. Travel nearbyAugust 30, 2018 at 5:26 PM

    Thanks have been given the opportunity to comment. Hopefully what you provided is useful for all those who need them. Visit my website if you want to know more about.Latest Breaking News in India
    Top Stories News Headlines

    ReplyDelete
    Replies
      Reply
  7. Travel nearbyNovember 22, 2018 at 4:29 PM



    Travel Nearby Places to visit in Uttarakhand
    Best Tourist Places to visit in Haridwar
    Tourist Places to Visit in Nainital
    Beautifull Hill Station Auli for Couples
    Tourist Place Near Bhimtal
    Most Beautiful Places To Visit in Ranikhet
    Tourist Places to Visit in Dehradun
    Places to visit in Dhanaulti
    Places to visit in Mussoorie

    ReplyDelete
    Replies
      Reply
  8. Travel nearbyDecember 15, 2018 at 11:18 AM

    Thanks a bunch for sharing this with all of us you actually know what you are talking about! Bookmarked. Please also visit my site
    Most famous tourist Places to visit in Rajasthan
    Best Tourist Places to visit in Jaipur
    Stunning Tourist Places to Visit in Jaisalmer
    Beautifull Hill Station Udaipur for Couples
    Incredible Places To Visit in Mount Abu
    Alluring Tourist Places To Visit in Jodhpur
    Most Tourist Places to Visit in Pushkar

    ReplyDelete
    Replies
      Reply
  9. Travel nearbyFebruary 1, 2019 at 3:10 PM

    Beautiful Places To Visit in Guwahati
    Stunning Tourist Places To Visit in Barpeta
    Amazing Places To Visit in Goalpara
    Most Beautiful Places To Visit in Dispur
    Most Beautiful Places To Visit in Digboi
    Stunning Tourist Places To Visit in Jorhat
    Most Amazing Places To Visit in Karimganj
    Beautiful Places To Visit in Nalbari
    Incredible Tourist Places To Visit in Tinsukia
    Popular Tourist Places To Visit in Tezpur

    ReplyDelete
    Replies
      Reply
  10. Travel nearbyFebruary 12, 2019 at 5:02 PM


    Beautiful Tourist Places To Visit in Meghalaya
    Amazing Places To Visit in Tura
    Best Tourist Places To Visit in Jowai
    Most Beautiful Places To Visit in Cherrapunji
    Incredible Tourist Places To Visit in Nongpoh
    Most Famous Places To Visit in Shillong
    Beautiful Places To Visit in Nongstoin

    ReplyDelete
    Replies
      Reply
  11. Travel nearbyMarch 2, 2019 at 5:20 PM


    Thanks a bunch for sharing this with all of us you actually know what I’m excited to find this page. I wanted to thank you for ones time due to this wonderful read!!

    Top 11 Most Beautiful Places To Visit in Arunachal Pradesh
    Most Beautiful Places To Visit in Bomdila & Things To Do
    Top 6 Alluring Tourist Places To Visit in Changlang & Things To Do
    Top 5 Stunning Tourist Places To Visit in Dirang & Things To Do
    Top 7 Best Tourist Places To Visit in Itanagar & Things To Do
    Top 7 Incredible Tourist Places To Visit in Roing
    Top 8 Best Tourist Places To Visit in Tawang
    Most Famous Tourist Places To Visit in Ziro & Things To Do
    Beautiful Tourist Places To Visit in Pasighat

    ReplyDelete
    Replies
      Reply
  12. Study WalaMarch 16, 2020 at 1:05 PM

    UP 12th Board Result click here

    ReplyDelete
    Replies
      Reply
Add comment
Load more...

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape