Skip to main content

Posts

Showing posts with the label Anonymous types

Anonymous types - sorting & working with Linq

Consider the following code        var numbers = new int[] { 1, 4, 6, 2, 9, 10, 0, 99, 33 };             var sortedNums = from n in numbers                              orderby n descending                              select n;             foreach (var v in sortedNums)                 Console.WriteLine(v);             var sports = new string[] { "soccer", "baseball" };             var Name = from sport in sports select new { Title = sport };             foreach (var s in Name)                 Console.WriteLine(s.Title); Line 3 sorts the arr...

Anonymous types - Examples

Simple   var simple = "Simple Ann Type";     string str= "Simple Ann Type"; Both the code are identical for MSIL Array Initializer var name = new string[] { "a","b","c" }; Console.WriteLine(name[0]); Composite Anonymous Types We can think of this use of anonymous types as defining an inline class without all of the typing.     var Person = new {FirstName="Bill", LastName="Clinton"};           Console.WriteLine(Person);//will produce - {FirstName="Bill", LastName="Clinton"}           Console.WriteLine(Person.FirstName);//will produce - Bill           Console.WriteLine(Person.LastName);//will produce - Clinton           //Person.FirstName = "s"; - ERROR : Error 1 Property or indexer AnonymousType#1.FirstName' cannot be assigned to -- it is read only   Console.ReadLine(); A nice feature added to anon...

Basic rules for using anonymous types

Anonymous types must always have an initial assignment and it can’t be null because the type is inferred and fixed to the initializer. can be used with simple or complex types can be used as initializers in for loops can be used and has to be used for array initializers can be used with arrays can be returned from methods but must be cast to object cannot be used for a class field

Anonymous types for dummies

Anonymous types are used to define strong types without defining the type. Anonymous types are strongly typed and checked at compile time. It provides a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. Anonymous types are reference types that derive directly from object. The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object. This type is widely used by LINQ, because LINQ returns dynamically-shaped data, whose type is determined by the LINQ query To understand better look at the following code static void Main ( string [] args)         {                 string [] names = { "Abhi1" , "abhi" , "abhi11"...