Sunday 18 October 2009

Anonymous Type Tricks - a clarification

The other day, I posted about using anonymous types to pass multiple pieces of state into a method - reminder:

byte[] resp = client.Post(destUri, new {
id = 100021,
dob = DateTime.Today,
caption = "Hello world"
About the same time Ayende Rahien posted about a related but different use in Entity Framework - example:

e => new {
manager = e.Manager.Id
thisIsADiscriminator = “E”

There is an important distinction between the two; in the first example, the property names (in the anonymous type) are only relevant to the caller. In the second (EF), the names are relevant to the callee. This is a huge difference. I don't know enough about EF to say more, but just a note: if you are doing something like this for your own types, please use a named property object to pass expected state into a method. Think of the kittens.

Novel uses of anonymous type initializers

On a related note; there was an interesting stackoverflow question today that shows another use of the anonymous type syntax - for specifying multiple members in a type-safe way:

IncludeProperties<IUser>(u => new {
u.ID, u.LogOnName, u.HashedPassword });

The important thing to note is that the above is an Expression (not a delegate), and the code inside tears the Expression apart to find the properties that we are interested in. It never actually invokes the code as a delegate, nor does it ever actually instantiate the anonymous type. It might just be me, but I thought that was quite cute ;-p