Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# anonymous type question

In the following code why are the variables c2 and c3 of a different anonymous type?

Thanks in advance for any advice and ... cheers !

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            var c1 = new Customer { Name = "Mark", Country = "USA" };

            var c2 = new { c1.Name, c1.Country };   //"<>f__AnonymousType0`2"
            var c3 = new { c1.Country, c1.Name };   //"<>f__AnonymousType1`2"
        }
    }

    public class Customer
    {
        public string Name { get; set; }
        public string Country { get; set; }
    }
}
like image 536
HerbalMart Avatar asked Dec 27 '22 16:12

HerbalMart


1 Answers

Because you initialized their properties in different orders.

They'll only be compiled to the same anonymous type if you initialize them in the same order. From the MSDN docs on anonymous types:

If two or more anonymous types in the same assembly have the same number and type of properties, in the same order, the compiler treats them as the same type.

like image 123
BoltClock Avatar answered Jan 15 '23 05:01

BoltClock