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.
Remember Me
a@href@title, i, strike, u
Copyright © 2003-2010 Falafel Software Inc.
The opinions expressed herein are Falafel's employees own personal opinions and do not represent Falafel Software's view in any way in case they go bananas!