Page 100 - CSharp/C#
P. 100

Generic methods with anonymous types


        Generic methods allow the use of anonymous types through type inference.


         void Log<T>(T obj) {
             // ...
         }
         Log(new { Value = 10 });


        This means LINQ expressions can be used with anonymous types:


         var products = new[] {
             new { Amount = 10, Id = 0 },
             new { Amount = 20, Id = 1 },
             new { Amount = 15, Id = 2 }
         };
         var idsByAmount = products.OrderBy(x => x.Amount).Select(x => x.Id);
         // idsByAmount: 0, 2, 1


        Instantiating generic types with anonymous types



        Using generic constructors would require the anonymous types to be named, which is not
        possible. Alternatively, generic methods may be used to allow type inference to occur.


         var anon = new { Foo = 1, Bar = 2 };
         var anon2 = new { Foo = 5, Bar = 10 };
         List<T> CreateList<T>(params T[] items) {
             return new List<T>(items);
         }

         var list1 = CreateList(anon, anon2);


        In the case of List<T>, implicitly typed arrays may be converted to a List<T> through the ToList
        LINQ method:


         var list2 = new[] {anon, anon2}.ToList();


        Anonymous type equality


        Anonymous type equality is given by the Equals instance method. Two objects are equal if they
        have the same type and equal values (through a.Prop.Equals(b.Prop)) for every property.


         var anon = new { Foo = 1, Bar = 2 };
         var anon2 = new { Foo = 1, Bar = 2 };
         var anon3 = new { Foo = 5, Bar = 10 };
         var anon3 = new { Foo = 5, Bar = 10 };
         var anon4 = new { Bar = 2, Foo = 1 };
         // anon.Equals(anon2) == true
         // anon.Equals(anon3) == false
         // anon.Equals(anon4) == false (anon and anon4 have different types, see below)






        https://riptutorial.com/                                                                               46
   95   96   97   98   99   100   101   102   103   104   105