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