次の方法で共有


C# 3.0 Anonymous Types

I have been playing around with some of the new C# 3.0 features, and I really have to say that I like the anonymous types. In reality, they do not present a great advantage over typical code defined classes, but they are simple and easy to use and require a lot less code. I really like the fact that they are immutable as well, so the properties that are created by the compiler are read-only. This is great if you need to create a read-only type that contains data from external sources in your application. One very common use for this is going to be LINQ. In a few lines of code, you can read the data from the source and then populate an anonymous type so that you have a .NET type-safe representation of the data to use in your application.

The basic syntax for an anonymous type is: 

 var anon_type_vehicle = new
{
    Make = "Ford",
    Model = "F-150",
    Weight = 6650.50D,
    Year = 2007
};

Console.WriteLine(anon_type_vehicle.Year.ToString())

This creates an immutable type that has 4 properties (System.String, System.String, System.Double, System.Int32).  This would write "2007" to the console as expected.

Another of the cool features of this is nesting the types:

 var anon_type_vehicle = new
{
    Make = "Ford",
    Model = "F-150",
    Weight = 6650.50D,
    Year = 2007,
    Dimensions = new
        {
            Length = 211.2,
            Width = 78.9,
            Height = 73.5
        }
};

Console.WriteLine(anon_type_vehicle.Dimensions.Height.ToString());

As you can see this is much easier than writing a class definition, and then referencing the class and filling in the values.  The limitations are that you can not change any of the fields once they have been created and you cannot write any methods for the type.  But to me, this is great for storing referenced data in your application.

Comments