Archives

Archives / 2007 / April
  • Two Notes About Anonymous Types

    1. The example of anonymous types from the C# 3.0 specification document is as follows:
      class __Anonymous1
      {
      	private T1 f1 ;
      	private T2 f2 ;
      	// …
      	private Tn fn ;
      
      	public T1 p1 { get { return f1 ; } set { f1 = value ; } }
      	public T2 p2 { get { return f2 ; } set { f2 = value ; } }
      	// …
      	public Tn pn { get { return fn ; } set { fn = value ; } }
      }
      

      But why would you need properties? Aren't public fields enough? It's not as if a person has written this type or that it would ever be manually mantained or even looked at.
      (For the record: Object initializers work just as well with fields)
    2. An interesting concept regarding anonymous types was raised by a fellow user-group member, whose name escapes me, about optimization:
      Should I have the following code:
      var myValue = new { A = 2, B = 3 };
      It might prove faster to simply declare the new anonymous type as a value type and place it on the containing method's stack.
      This raised more thoughts about where the anonymous type should be placed - my view is that an anonymous type contained in a method (as it probably would, unless you trick it) should be a nested type of the method's containing type. This, in turn, both removes clutter from the namespace and allows the anonymous type to more easily adapt to the parent's generic parameters:
      class A<T> where T : new()
      {
          void B()
          {
              var myValue = new { C = new T() };
          }
      }
      
      // Turns into:
      
      class A<T> where T : new()
      {
      // Note the use of a value type for a small type struct __Anonymous1 { private T c; public T C { get { return c; } set { c = value; } } } void B() { __Anonymous1 myValue = new __Anonymous1(); myValue.C = new T(); } }
      The only caveat is when the type is to be nested in a generic type, but doesn't use the generic parameter/s, it will be doomed to get re-JITed every time a different type calls is for no reason.

    Read more...