Saturday 23 December 2017

Anonymous Types


  • Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object.
  • The compiler provides a name for each anonymous type, although your application cannot access it.
  • You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type.
  • You cannot declare a formal parameter of a method, property, constructor, or indexer as having an anonymous type.
  • To pass an anonymous type, or a collection that contains anonymous type, as an argument to a method, you can declare the parameter as type object.
  • Two instances of the same anonymous type are equal only if all their properties are equal.
  • anonymous types typically used in the 'Select' clause of a query expression to return a subset of properties from each object in the source sequence.
    eg:- LINQ Query expression.
    var anonymousData = from pl in data select new {pl.Fname, pl.Lname};
  • Anonymous type contain one or more public read-only properties.
  • We can create anonymous types by using 'new' keyword together with the object initializer.
    eg:- var anonymousData = new {Fname="Vivek", Lname="Sharma"};
  • Anonymous type is a way to define read-only properties into a single object without having to define type explicitly.
  • Anonymous type throws compile time errors.

No comments:

Post a Comment