views:

61

answers:

3

Hi,

I got a scenario to create the anonymous list from the anonymous types, and i achieved that using

    public static List<T> MakeList<T>(T itemOftype)
    {
        List<T> newList = new List<T>(); 
        return newList; 
    } 

    static void Main(string[] args)
    {
       //anonymos type
       var xx = new
       {                             
          offsetname = x.offName,
          RO = y.RO1
       };

       //anonymos list
       var customlist = MakeList(xx);

       //It throws an error because i have given the wrong order
       customlist.Add(new { RO = y.RO2, offsetname = x.offName });
       customlist.Add(new { RO = y.RO3, offsetname = x.offName });

       //but this works
       customlist.Add(new { offsetname = x.offName, RO = y.RO2 });
       customlist.Add(new { offsetname = x.offName, RO = y.RO3 });
    }

these are the error messages

System.Collections.Generic.List.Add(AnonymousType#1)' has some invalid arguments

Argument '1': cannot convert from 'AnonymousType#2' to 'AnonymousType#1'

whats the reason behind that??

Cheers

RameshVel

+4  A: 

Yes, it's important.

Two anonymous type initializers use the same auto-generated type if the property names and types are the same, in the same order.

The order becomes relevant when hashing; it would have been possible for the type to be generated with a consistent order for calculating a hash value, but it seems simpler to just include the property order as part of what makes a type unique.

See section 7.5.10.6 of the C# 3 spec for details. In particular:

Within the same program, two anonymous object initializers that specify a sequence of properties of the same names and compile-time types in the same order will produce instances of the same anonymous type.

Jon Skeet
thanks jon for the clarification..
Ramesh Vel
Gishu
@Gishu: I think it probably makes the compiler simpler, so I think the onus is on those who want it to *not* matter to give a compelling reason why it shouldn't :)
Jon Skeet
+2  A: 

Yes, the order of fields is significant. Same fields, different order will yield different types.

From the language specification:

"Within the same program, two anonymous object initializers that specify a sequence of properties of the same names and compile-time types in the same order will produce instances of the same anonymous type. "

Brian Rasmussen
Brian, thanks for the clarification..
Ramesh Vel
+1  A: 

whats the reason behind that??

Suppose that order did not matter. Suppose you were on the compiler team. Describe for me the exact behaviour of an implementation of "ToString" on such an anonymous type, such that the implementation meets all user expectations.

I personally cannot come up with one, but perhaps you can.

Eric Lippert
on ToString() in anonymous types yield different results on the same data but in different order.. thanks, now i can relate this to the calculating hash values..
Ramesh Vel