Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Anonymous methods in C#?

What is anonymous method in C#?

A method without a name is called as an anonymous method is, the delegate operator creates an anonymous method that can be converted to a delegate type.

What is use of anonymous methods in C#?

  • You can use an anonymous method to create an anonymous function with unnamed inline code.
  • C# 2.0 introduced the concept of anonymous methods to write unnamed inline statement blocks that can be executed in a delegate invocation.

How to create and use anonymous method?

An anonymous method behaves like a regular method and allows us to write inline code in place of explicitly named methods.

Code example

//declare delegate
delegate void displayFullName(string fname, string mName, string lName);
 
//instantiate delegate with anonymous method
displayFullName fullName = delegate (string fname, string mName, string lName) {
    Console.WriteLine("Full name: " + fname + " " + mName + " " + lName);
   };


 
//anonymous method with generic action delegate
Action<string, stringstring> userFullName = delegate (string fname, string mName, string lName)
{
  Console.WriteLine("User full name: " + fname + " " + mName + " " + lName);
}; 

Anonymous function in C#

 What is anonymous function in C#?

An anonymous function is an "inline" statement or expression that can be used wherever a delegate type is expected.

You can use it to initialize a named delegate or pass it instead of a named delegate type as a method parameter.

You can use a lambda expression or an anonymous method to create an anonymous function. We recommend using lambda expressions as they provide more concise and expressive way to write inline code.

Reference…https://docs.microsoft.com/

How to use anonymous function in C#?

Anonymous function code examples using,

  • Delegate with named method,
  • Lambda expression
  • Delegate with anonymous method
  • Built-in delegates (Func & Action delegates)


delegate void SampleDelegate(string x);

    

public class AnonymousFunctions
    {
         static void DisplayData(string x)
        {
            Console.WriteLine("Data is :" + x);
        }
        static void AnonymousSamples()
        {
            // initialization with a named method.
            SampleDelegate testNamed = new SampleDelegate(DisplayData);
 
            // C# 2.0: A delegate can be initialized with
            // inline code, called an "anonymous method." This
            // method takes a string as an input parameter.
            SampleDelegate TestAnMethod = delegate (string s) { Console.WriteLine(s); };
 
            // C# 3.0. A delegate initialization with a lambda expression.
            // The lambda also takes a string
            // as an input parameter (x). The type of x is inferred by the compiler.
            SampleDelegate TestLambdaExp = (x) => { Console.WriteLine(x); };
 
            //Anonymous function with action generic delegate
            Action<string> TestDelGeneric = (s) => { Console.WriteLine(s); };
 
            // Anonymous function with action delegate without paremeters.
            Action TestDelActGen = () => { Console.WriteLine("Codechef4U samples"); };
 
            //Anonymous Function with func generic delegate, first 2
            // parameters are input, and last parameter is result
            Func<string, string, string> GetCombinedString = (x, y) => { return x+ " " + y; };
 
            //Anonymous Function with predicate generic delegate
            Predicate<string> isValidSurName = (x) => { return x != null && x.Length >2 ? true : false; };
 
            // Invoke the delegates.
            DisplayData("The named method call using delegate .");
            TestAnMethod("The anonymous method call.");
            TestLambdaExp("The lambda call.");
            TestDelGeneric("The action generic delegate .");
            TestDelActGen();
            Console.WriteLine("Full name is: "+ GetCombinedString("Aditya", "Kendre"));
            Console.WriteLine("Is valid name :" + isValidSurName("Kendre"));
        }
    } 

Anonymous Types in C#

What is Anonymous Type in C#?

Anonymous types are easy way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.

In simple language anonymous type is a class without name containing only read-only public properties.

Note:

  • The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.
  • If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them.

How to create and use anonymous types in C#?

The following first example shows an anonymous type that is initialized with two properties named Id and Name.
Following 2nd example Anonymous type “ITDepartment” created with LINQ query select clause, first parameter is not named but used inferred anonymous type member(compiler gives name of department id) name and another parameter is named “depName”.

Example:

    public void ExmployeeData()
        {
            var Departments = GetAllDepartments();
 
            //1.  anonymous type “Employee” with properties named Id and Name.
            var Employee = new { Id="sk14",Name = "Shourya" };
 
            //2. anonymous type "ITDepartment" with LINQ query filter
            var ITDepartment = from dep in Departments
                               where dep.Name == "IT"
                               select new {dep.Id, DepName = dep.Name };
            //how to use it?
            Console.WriteLine("Employee Id :" + Employee.Id);
            Console.WriteLine("Employee Id :" + Employee.Name);
            Console.WriteLine("Employee Department Name :" + ITDepartment.FirstOrDefault().DepName); 
        }


Sample class and method to create in memory department collection.

   public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }


public List<Department> GetAllDepartments()
        {
            var departments = new List<Department>();
 
            var ITDepartment = new Department
            {
                Id = 1,
                Name = "IT"
            };
 
            var AccountDepartment = new Department
            {
                Id = 2,
                Name = "Account"
            };
            departments.Add(ITDepartment);
            departments.Add(AccountDepartment);
 
            return departments;

        } 



How to return anonymous type with Web API?

In follwing code example web method returns anonymous type "Employee"

[HttpGet]
[Route("GetEmployeeData")]
 public IHttpActionResult GetEmployeeData()
   {
       //anonymous type Employee with properties named Id and Name.
       var Employee = new { Id = "sk14", Name = "Shourya" };
       // Status Code 200;
        return this.Ok(Employee);
   }

 

How to return anonymous type with method?

      //Return anonymous Type as object
        public object GetAnonymousData()
        {
            return new { Id = "sk14", Name = "Shourya" };
        }


       //Display anonymous Type values from object
        public void DisplayAnonymousData()
        {
            object refobj = GetAnonymousData();
            Type type = refobj.GetType();
            PropertyInfo[] fields = type.GetProperties();
            foreach (var field in fields)
            {
                string name = field.Name;
                var firstValue = field.GetValue(refobj, null);
                Console.WriteLine("Employee Name " + firstValue);
            }
        }