Anonymous types allow us to create new types without defining them. This is a way of defining read-only properties in a single object without having to define each type explicitly. Here, Type is generated by the compiler and is accessible only for the current block of code. The type of properties is also inferred by the compiler.
We can create anonymous types by using “new” keyword together with the object initializer.
Example
- var anonymousData = new
- {
- ForeName = "Jignesh",
- SurName = "Trivedi"
- };
- Console.WriteLine("First Name : " + anonymousData.ForeName);
Anonymous Types with LINQ Example
Anonymous types are also used with the "Select" clause of LINQ query expression to return a subset of properties.
Example
If any object collection has properties calling FirstName, LastName, DOB, etc... and you want only FirstName and LastName after the Querying the data, then:
- class MyData {
- public string FirstName {
- get;
- set;
- }
- public string LastName {
- get;
- set;
- }
- public DateTime DOB {
- get;
- set;
- }
- public string MiddleName {
- get;
- set;
- }
- }
- static void Main(string[] args) {
-
- List < MyData > data = new List < MyData > ();
- data.Add(new MyData {
- FirstName = "RASH", LastName = "BIHTI", MiddleName = "G", DOB = new DateTime(1990, 12, 30)
- });
- data.Add(new MyData {
- FirstName = "VIKI", LastName = "HAYEN", MiddleName = "G", DOB = new DateTime(1995, 11, 6)
- });
- data.Add(new MyData {
- FirstName = "NEWWES", LastName = "TR", MiddleName = "G", DOB = new DateTime(1993, 10, 8)
- });
- data.Add(new MyData {
- FirstName = "Amit", LastName = "Vyas", MiddleName = "P", DOB = newDateTime(1983, 6, 15)
- });
- data.Add(new MyData {
- FirstName = "Yash", LastName = "Pandiya", MiddleName = "K", DOB = newDateTime(1988, 7, 20)
- });
- }
- var anonymousData = from pl in data
- select new {
- pl.FirstName, pl.LastName
- };
- foreach(var m in anonymousData) {
- Console.WriteLine("Name : " + m.FirstName + " " + m.LastName);
- }
- }