blog

Home / DeveloperSection / Blogs / Anonymous in C#

Anonymous in C#

priyanka kushwaha2232 10-Mar-2015

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;

delegatevoidNumberChanger(int n);

 

namespace AnonTypes

{

    classProgram

    {

        staticint num = 10;

        publicstaticvoid AddNum(int p)

        {

            num += p;

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

        }

        staticvoid 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


Updated 22-Feb-2018

Leave Comment

Comments

Liked By