#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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: