Tuesday, September 12, 2017

Anonymous Types

An anonymous type is a simple class generated by the compiler within IL to store a set of values. var data type and new keyword is used to create an anonymous type.

Ex:
  1. var emp = new { Name = "xxx",Salary=100 };

  2. When the code will be compiled it will generate full fledged Anonymous Class with all these properties.

  3. It is very helpfull in LINQ when we want to create some new class with limited properties from the existing Class.
  4. Ex:
  5. var result =from obj in Collection
  6. select new
  7. {
  8. Name = obj.PropertyName,
  9. Address= obj.PropertyAddress
  10. };
  11. In this Example It is creating an anonymous class with two properties taking the values from obj. There may be lots of properties with existing object but we are selecting only few.We may include some filtration in query.

No comments:

Post a Comment