Skip to content

#4 Anonymous Types

It is a class type variable without any name, that can contain only read-only properties. It cant contain other members, such as fields, methods, events etc.

var student = new { Id = 1, FirstName = "Tejaswi", LastName = "Pandava" };

Anonymous types can only be held by var. and the fields within it are read-only so you cant update the FirstName. To access the fields (FirstName) you could use the (.) operator as it’s a class type variable.

var student = new { Id = 1, FirstName = "Tejaswi", LastName = "Pandava", Address = new { Id = 1, City = "Hyderabad", Country = "India" } };
Console.WriteLine(student.Id); //output: 1
Console.WriteLine(student.FirstName); //output: Tejaswi
Console.WriteLine(student.LastName); //output: Pandava

student.Id = 2;//Error: cannot change value
student.FirstName = "Steve";//Error: cannot change value

It supports holding other anonymous types and also array of anonymous types. This is mainly used in LINQ queries.

class Program
{
    static void Main(string[] args)
    {
        IList<Student> studentList = new List<Student>() { 
            new Student() { StudentID = 1, StudentName = "Teja", age = 18 },
            new Student() { StudentID = 2, StudentName = "Raja",  age = 21 },
            new Student() { StudentID = 3, StudentName = "Vamsi",  age = 18 },
            new Student() { StudentID = 4, StudentName = "Ram" , age = 20  },
            new Student() { StudentID = 5, StudentName = "Akshay" , age = 21 } 
        };

        var students = from s in studentList
                       select new { Id = s.StudentID, Name = s.StudentName };

        foreach(var stud in students)
            Console.WriteLine(stud.Id + "-" + stud.Name);
    }
}

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public int age { get; set; }
}
Published inC#

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *