• 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
Showing posts with label Anonymous Types. Show all posts
Showing posts with label Anonymous Types. Show all posts

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 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Older Posts

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