Ad-hoc data structuring with anonymous types

I've been experimenting with the anonymous types we have in C# 3.0, here's my latest creation:

var actions = new[]
{
new { Name = ActionSave, Type = KnownActionType.Save },
new { Name = ActionCopy, Type = KnownActionType.Copy },
new { Name = ActionNew, Type = KnownActionType.New },
// snipped another 10 actions...
};
foreach (var action in actions)
{
Actions.Add(new Action(action.Name, action.Type));
}

C# happily compiled this for me, to my surprise.  And it works just as I expected it to.


image


Even intellisense picked it up properly.  See, strongly typed goodness.


The most amazing part I wasn't expecting is the C# compiler knowing that all the array items are the same anonymous type.  So it must have worked that bit out somewhere.


---


Prior to the amazing var variable, you would to do this with nasty looking nested object[] setup.  Like so:


(warning, untested code)

object actions = new object[]
{
new object[] { ActionSave, KnownActionType.Save },
new object[] { ActionCopy, KnownActionType.Copy },
new object[] { ActionNew, KnownActionType.New },
// snipped another 10 actions...
};
foreach (object action in actions)
{
// reall awful looking line next
Actions.Add(new Action((string)action[0], (KnownActionType)action[1]));
}



There are heaps of things wrong with this old way:



  • No type safety - do your own casting

  • No array-size safety - index 0 or 1 may not exist

  • Boxing with KnownActionType

 


Yes.  I think I'm going to do nested anonymous types next.


jliu