[C# 3.0+] Annonymous Types

What Does it do?

Annonymous Types

var annon = new { name1 = var1, name2 = var2, ... };
// or
obj annon = new { name1 = var1, name2 = var2, ... };

// Example
obj results = new { OriginalRequest = myRequest, Data = foundData, Status = dataStatus };
// Now you can see results.Data!

Limitations
I had originally wanted to use this to pass a complex, dynamic object back from a function, however, I soon found out that this was not possible [without the use of reflection]:

From Rick Strahl’s Blog
One very important aspect to understand about anonymous types is that they are a compiler generated construct. The type is a regular .NET type similar to any other but it has one big limitation: Anonymous types are scoped only to the currently executing method. Because the generated type is anonymous there’s no public name for the type that you can access. In other words you can’t instantiate the type directly on your own and you can’t reference the type outside of the method that created it.



Tags:
This entry was posted on Friday, October 9th, 2009 at 8:56 am and is filed under c#. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “[C# 3.0+] Annonymous Types”

  1. Dan

    So… It’s a runtime-only association list with severe scope restrictions?

    Language design fail.

  2. admin

    Yeah, at first I thought it was a really cool concept given what I *thought* I could do with it… but then as I got further along with it I figured out I couldn’t use it like that. Now I’m not sure what it *is* useful for.

Leave a Reply

Your comment