Archive for category Anonymous Types

Can You Pass an Anonymous Type Across Functions?

One of the biggest questions with Anonymous Types is “can I pass them around?” If not, why not? Can you do something like this, for example:

var GetAnonymousValue() {
  return new { Name = "Richard Bushnell" };
}

void Main() {
  var value = GetAnonymousValue();
  var name = value.Name;
}

The answer is simple: no, you can’t pass anonymous types across functions. var is not a dynamic variable, like in JavaScript. The CLR knows nothing about “var”, as the compiler just uses it to infer types when a variable is initialized.

At least, that was the answer until now. Using a simple extension method and generics, Alex James just showed a nice way to pass them around on his blog.

The trick is to use an example of the anonymous type you expect.

object GetAnonymousValue() {
  return new { Name = "Richard Bushnell" };
}

void Main() {
  var value = GetAnonymousValue().CastByExample(new { Name = "" });
  var name = value.Name;
}

While this might be a little dangerous, especially if you’re not testing your code regularly, this could be the solution to a few problems I can already think of.

Watch out for casting exceptions at runtime though! If you make a mistake anywhere, you’ll won’t get a compile-time exception, but a nasty runtime exception instead.

No Comments