C-Sharp Anonymous Type

Anonymous type, is a type that doesn't have any name. it encapsulate a set of read-only properties into a single object without defining its type moreover it is reference type.

The type name is generated by the compiler when initialized. var keyword is used to hold reference of anonymous types.

Anonymous type object is created by using the new keyword and object initializer syntax It includes properties of different data types and properties with further more anonymous type.

We can create anonymous type object as follows.

using System; namespace SWClass { class Program { static void Main(string[] args) { var anonymousTypeVar = new { stringProperty = "First Property", intProperty = 2, boolProperty = true }; string s = $"String: {anonymousTypeVar.stringProperty} int: {anonymousTypeVar.intProperty} bool: {anonymousTypeVar.boolProperty}"; Console.WriteLine(s); s = $"String: {(anonymousTypeVar.stringProperty.GetType())} int: {anonymousTypeVar.intProperty.GetType()} bool: {anonymousTypeVar.boolProperty.GetType()}"; Console.WriteLine(s); Console.ReadKey(); } } }

OUTPUT: String: First Property int: 2 bool: True String: System.String int: System.Int32 bool: System.Boolean

We can also create anonymous type as an properties of anonymous type object

using System; namespace SWClass { class Program { static void Main(string[] args) { var Student = new { StudentId = 1, Class = "2nd", RollNo = 12, Name = "Jhon Astin", Address = new { HouseNo = "#43", City = "Oakdale", State = "Tennessee", Country="United State", Zip = 37829 }, }; string s = $"Student Info: {Student.Name} ({Student.RollNo}) Address: {Student.Address.HouseNo}, {Student.Address.City}, {Student.Address.Country}, {Student.Address.Zip}"; Console.WriteLine(s); Console.ReadKey(); } } }

OUTPUT: Student Info: Jhon Astin (12) Address: #43, Oakdale, United State, 37829 Anonymous types are class types that derive from object, and we cannot be cast to any type except object.

We cannot declare a field, a property, an event, or the return type of a method as having an anonymous type.

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories