In this blog, I’m explaining about Anonymous in C#


What is Anonymous?

Anonymous types allow us to create a new type without defining them. This is a way of defining read-only properties into a single object without having to define type explicitly.

Restrictions of Anonymous Type class

  • Anonymous class can contain only public fields.
  • Anonymous class’s fields must all be initialized.
  • Anonymous class member never is static.
  • Anonymous cannot implement the interface.
Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

delegate void NumberChanger(int n);

 

namespace AnonTypes

{

    class Program

    {

        static int num = 10;

        public static void AddNum(int p)

        {

            num += p;

            Console.WriteLine("Name method:{0}", num);

        }

        static void Main(string[] args)

        {

            var p = new { Name = "Avon", Price = "3000" };

            Console.WriteLine("Name={0}\n price={1}", p.Name, p.Price);

            //Anonymous methods

            NumberChanger nc = delegate(int x)

            {

                Console.WriteLine("Anonymous method:{0}", x);

            };

            nc(10);

          

        }

    }

}

Output:


Name=Avon

Price=3000

Anonymous method=10

  Modified On Feb-22-2018 04:06:50 AM

Leave Comment