The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 2,975 other subscribers

Archive for November 12th, 2013

.net/C#: you can pass anoymous types to a generic method, but not return them as a method result

Posted by jpluimers on 2013/11/12

You can pass anonymous types to a method, if that method has a generic parameter type. I regularly use this to Resolving a parameter name at runtime using the Generic Type Cache technique described by Rinat Abdullin.

The other way around however is impossible, as return types cannot, as Alexander M. Batishchev writes in his StackOverflow answer:

You can’t.

You can only return object, or container of objects, e.g. IEnumerable

Jared Par does a bit more elaboration:

You cannot type any method in C# to be the explicit type of an anonymous types. They cannot be “named” so to speak and hence cannot appear in metadata signatures.

If you really want to return a value which is an anonymous type there are 2 options

  • Have the return type of the method be System.Object. You can then do evil casting hacks to get a typed value in another method. This is very fragile and I don’t recommend it.
  • Use a generic method and a type inference trick to get the return type correct. This would require a very interesting signature definition for your approach.

Anonymous types were not really meant to be passed around in this fashion. At the point you need to pass them around between your functions in this manner, you’re better off explicitly defining a type.

Bummer (:



Posted in .NET, .NET 2.0, .NET 3.0, .NET 3.5, .NET 4.0, .NET 4.5, C#, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Development, Software Development | Leave a Comment »

%d bloggers like this: