navigation
 Friday, January 29, 2010

I came across an interesting technique earlier this week. Did you know that you can return an anonymous type from a method and still have strongly typed access to its members? I got this technique from Tomas Petricek’s blog. Here is a quick example of how it works; for details of why it works please see the original article.

        private static object ReturnAnon()
        {
            return new { FirstName = "Captain", MiddleName = "Jack", LastName = "Sparrow" };
        }

        private static T Cast<T>(object o, T type)
        {
            return (T)o;
        }

        static void Main(string[] args)
        {
            var anon = Cast(ReturnAnon(), new { FirstName = "", MiddleName = "", LastName = "" });
            Console.WriteLine(String.Format("FirstName: {0}", anon.FirstName));
            Console.WriteLine(String.Format("MiddleName: {0}", anon.MiddleName));
            Console.WriteLine(String.Format("LastName: {0}", anon.LastName));
            Console.ReadLine();
        }

Of course, just because you can return an anonymous type doesn’t mean that you should. As a general rule, I would say that if you are using the method’s return value in only one place, then it is OK to use this technique. However, the moment that the method is used from a second place, that anonymous type should be explicitly declared instead.

Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, i, strike, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview