Page 99 - CSharp/C#
P. 99

Chapter 9: Anonymous types




        Examples



        Creating an anonymous type


        Since anonymous types are not named, variables of those types must be implicitly typed (var).


         var anon = new { Foo = 1, Bar = 2 };
         // anon.Foo == 1
         // anon.Bar == 2


        If the member names are not specified, they are set to the name of the property/variable used to
        initialize the object.


         int foo = 1;
         int bar = 2;
         var anon2 = new { foo, bar };
         // anon2.foo == 1
         // anon2.bar == 2


        Note that names can only be omitted when the expression in the anonymous type declaration is a
        simple property access; for method calls or more complex expressions, a property name must be
        specified.


         string foo = "some string";
         var anon3 = new { foo.Length };
         // anon3.Length == 11
         var anon4 = new { foo.Length <= 10 ? "short string" : "long string" };
         // compiler error - Invalid anonymous type member declarator.
         var anon5 = new { Description = foo.Length <= 10 ? "short string" : "long string" };
         // OK


        Anonymous vs dynamic


        Anonymous types allow the creation of objects without having to explicitly define their types ahead
        of time, while maintaining static type checking.


         var anon = new { Value = 1 };
         Console.WriteLine(anon.Id); // compile time error


        Conversely, dynamic has dynamic type checking, opting for runtime errors, instead of compile-time
        errors.


         dynamic val = "foo";
         Console.WriteLine(val.Id); // compiles, but throws runtime error







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