Excerpt from: Bill Blogs in C#
|
 |
| November 13, 2008 | | My last post on duck typing generated this question: I have a question regarding your recent post about Duck Typing and anonymous type scope in C# 4.0. Does this now open up the possibility of using an anonymous type (say, the results of a LINQ query) outside the scope of the method it was created? Something like the following using the example in your post: 1: public static void PrintLabel(dynamic thing) 2: { 3: Console.WriteLine("ID: {0}, Label: {1}", thing.ID, thing.Label); 4: } 5: 6: public void GetAnAnonymousType(string key) 7: { 8: var item = (from application in _Repository.GetApplications() 9: where application.ApplicationKey == key 10: select new 11: { 12: ID = application.ApplicationId, 13: Label = application.LastName 14: }).SingleOrDefault(); 15: 16: PrintLabel(item); 17: } Very simply, yes. This construct is a great use of dynamic types in C#. Dynamic provides a form of escape hatch into a a world where your types can be tested at runtime.  | | |
|
|