#654 – You Can’t Use an Anonymous Type Directly

An anonymous type is a temporary data type that is inferred based on the data that you include in an object initializer.  For example, the code below causes a class to be generated that contains three properties–Title, Year and Director.

var movie = new { Title = "Gladiator", Year=2000, Director = "Ridley Scott" };

When you declare an object with an anonymous type like this, the compiler automatically generates the type for you.  You can use ILDASM to look at the IL for this code and see the type.  It has a fairly cryptic name.

While the compiler creates a type to represent the object that you declared, you can’t reference this type explicitly in your code.

Advertisements

#653 – Projection Initializers

A projection initializer is a declaration for a member of an anonymous type that does not include a property name.

Here’s an example, where the members of the anonymous type are initialized using local variables.  The resulting property names in the anonymously-typed object match the variable names.

string title = "Seven Samurai";
string director = "Akira Kurosawa";
int year = 1956;

var movie = new { title, year, director };


You can also use properties of another object to initialize the anonymously-typed objects members.

            MovieInfo mi = new MovieInfo("Seven Samurai", "Akira Kurosawa", 1956);

            var movie = new { mi.Title, mi.Year, mi.Director };

#652 – Using Expressions and Variables in Anonymous Type Declarations

One way to declare an anonymous type is to specify the name of each property of the new type, along with the value of that property, expressed as a constant.

var movie = new { Title = "North By Northwest", Year = 1959, Director = "Alfred Hitchcock" };

When you declare an anonymously-typed object, you can use any expression as the value for a property.

// Note: GetFavMovie() returns a string
int birthYear = 1964;
var movie2 = new { Title = GetFavMovie(), Year = birthYear - 25, Director = movie.Director };

You can also leave off the named property and just include an named identifier representing a value.

        public static string Director { get; set; }
        private const int TheYear = 1956;

        static void Main()
        {
            string aMovieTitle = "Seven Samurai";
            Program.Director = "Akira Kurosawa";

            var movie2 = new { aMovieTitle, TheYear, Program.Director };
        }

The property names in the generated type will match the identifiers that you use.

#651 – Passing an Anonymously-Typed Object to a Method

An anonymous type is a temporary data type that is inferred based on the data that you include in an object initializer.

var movie = new { Title = "North By Northwest", Year = 1959, Director = "Alfred Hitchcock" };

You normally can’t pass this object to a method because there is no explicit type for the object and you cannot define an implicitly-typed parameter for a method.

However, you can use a dynamically-typed parameter (dynamic keyword) to pass the anonymously-typed object to a method.

    public static class MovieUtility
    {
        public static void DumpFromAnonType(dynamic anonType)
        {
            Console.WriteLine("Title = {0}", anonType.Title);
        }
    }

 

            var movie = new { Title = "North By Northwest", Year = 1959, Director = "Alfred Hitchcock" };
            MovieUtility.DumpFromAnonType(movie);

This code will compile and will execute properly if run. Passing an object that doesn’t have a Title property to the method will result in a run-time error.

#650 – Creating an Array of Anonymously-Typed Objects

An anonymous type is a temporary data type that is inferred based on the data that you include in an object initializer.  In addition to creating a single anonymously-typed object with an object initializer, you can also create an array of objects.

            var movies = new[] {
                new { Title = "North By Northwest", Year = 1959, Director = "Alfred Hitchcock" },
                new { Title = "Zelig", Year = 1983, Director = "Woody Allen" },
                new { Title = "King Kong", Year = 2005, Director = "Peter Jackson" }};

With this declaration, you end up with an array of anonymously-typed objects, each of which has the properties Title, Year, and Direction.

Note that this implicitly-typed array must contain elements of the same type, so each element must have the exact  same set of properties.

#649 – Creating an Anonymous Type

An anonymous type is a temporary data type that is inferred based on the data that you include in an object initializer.

We can use object initializer syntax to initialize an object:

Dog kirby = new Dog { Name="Kirby", Age=14 };

We can use the same syntax to initialize an object where we don’t mention a particular data type.  For example, we can declare/initialize an object that contains some information about a movie.

var movie = new { Title = "North By Northwest", Year = 1959, Director = "Alfred Hitchcock" };

Notice that we haven’t created a Movie class, but we now have an object that represents a movie which has three properties–Title, Year and Director.

The compiler has actually created a temporary “anonymous” type to represent the movie object.  Note also that the movie variable is implicitly typed (var keyword)since we don’t have a named type.

#648 – Using an Object Initializer

You typically initialize the data members of an object by invoking one of the object’s constructors and passing it any information that it requires.  For example:

Dog kirby = new Dog("Kirby", 14);

If a parameterless constructor exists for the class, you can alternatively create the object without invoking a constructor, using the object initializer syntax shown below.

Dog kirby = new Dog { Name="Kirby", Age=14 };

This is functionally equivalent to:

Dog kirby = new Dog();
kirby.Name = "Kirby";
kirby.Age = 14;

If a parameterless constructor does not exist for the class, you can still use the object initializer syntax, but only after explicitly invoking one of the constructors.