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. Here Type is generating by the compiler and it 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
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 are also used with the "Select" clause of LINQ query expression to return subset of properties.
Example
If Any object collection having properties called 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) {
- // Create Dummy Data to fill Collection.
- List < MyData > data = new List < MyData > ();
- data.Add(new MyData {
- FirstName = "Jignesh", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1990, 12, 30)
- });
- data.Add(new MyData {
- FirstName = "Tejas", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1995, 11, 6)
- });
- data.Add(new MyData {
- FirstName = "Rakesh", LastName = "Trivedi", 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);
- }
- }
Points to Remember :
- Anonymous type can be defined using the new keyword and object initializer syntax.
- The implicitly typed variable- var, is used to hold an anonymous type.
- Anonymous type is a reference type and all the properties are read-only.
- The scope of an anonymous type is local to the method where it is defined.
No comments:
Post a Comment