Home > DeveloperSection > Blogs > Anonymous in C#

Anonymous in C#


.NET C# 
Ratings:
0 Comment(s)
 709  View(s)
Rate this:

Anonymous in C#

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

What is Anonymous?

Anonymous types allow us to create new type without defining them. This is way to 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 are static.

·         Anonymous cannot implement 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


Don't want to miss updates? Please click the below button!

Follow MindStick