Getting values out of XML in .NET 3.5 (LINQ to XML series part 2)

In my last post I gave a brief introduction to some of the new XML classes available in .NET 3.5. In this post I’ll continue that introduction by explaining how to get information out of the XML.

First off, lets assume we have some XML that looks like this:

XElement root = new XElement("root",
    new XAttribute("Attribute", "TheValue"),
    new XElement("FirstChild"),
    new XElement("SecondChild", new XElement("Grandchild", "The content of the grandchild")));

or, if you prefer in XML format, like this:

<root Attribute=”TheValue”>

<FirstChild />

<SecondChild>

<Grandchild>The content of the grandchild</Grandchild>

</SecondChild>

</root>

There are a number of ways to get the content of the grandchild element. For example:

Console.WriteLine(root.Element("SecondChild").Element("Grandchild").Value);

Value returns a string which contains the content of the element specified. In the above case it will output:

The content of the grandchild

However, you need to watch out for when there are child elements of the thing you want the value of as their content is included when you get the value. For example, if the above XML is extended so that it looks like this:

<root Attribute=”TheValue”>

<FirstChild />

<SecondChild>

<Grandchild>The content of the grandchild

<Great-grandchild>GGC content</Great-grandchild>

<Grandchild>

</SecondChild>

</root>

And the above line of C# is executed again, the result is now:

The content of the grandchildGGC content

As you can see the content of the element you want plus its child elements are now returned. This may not necessarily be what you want.

There is a second way to get the content from an element. That is to use a casting operator. You can cast the element to a number of types. In this case to a string. for example:

Console.WriteLine((string)root.Element("SecondChild").Element("Grandchild"));

The result is the same as calling Value on the element.

Be careful here, because casting an element to a string will not have the same result as calling ToString() on an element. You can see that if you simply pass the element itself to writeline (which will then call ToString() for you). For example:

Console.WriteLine(root.Element("SecondChild").Element("Grandchild"));

The result is:

<Grandchild>The content of the grandchild

<Great-grandchild>GGC content</Great-grandchild>

</Grandchild>

The process is similar if you are dealing with attribute. Using the above XML as an example, an attribute value can be retrieved like this:

Console.WriteLine(root.Attribute("Attribute").Value);

Or, using the cast operator to a string like this:

Console.WriteLine((string)root.Attribute("Attribute"));

Both of the above pieces of code output the same thing: TheValue

If you were to call WriteLine on an XAttribute object you’ll see that the ToString() method returns something slightly different. It returns this: Attribute=”TheValue”

Lets say, for instance, that the Attribute had a value of 123.456, which is a valid number representation. I mentioned earlier about casting operators on XElement and XAttribute. Well, you can cast this to a double if you prefer to get the value in that type. There is no tedious converting in your own code as the framework can handle that for you. For example:

(double)root.Attribute("Attribute")

That’s it for this post. There will be more on XML and LINQ soon.

Introduction to LINQ to XML

Last year I wrote about the new languages features available in C# 3.0 (Anonymous Types, Extension Methods, Automatic Properties, A start on LINQ, Object Initialisers I, Object Initialisers II, & Object Initialisers III) and since then I’ve really got in to LINQ, especially LINQ to XML. The reason for that is that I hate XPath and I see LINQ to XML as a much easier way of querying XML files without faffing about with terse XPath strings. I would much rather have the ability to easily see what is going on with the query than have to figure out why my XPath isn’t working for me.

However, LINQ to XML is more than just new funky querying mechanisms. There is a whole new set of classes to deal with XML that are much easier and more intuitive than the classes that were provided back with .NET 1.0, in my opinion.

The main two classes in the new way of doing XML are XElement and XAttribute. For example, to create a new element:

XElement root = new XElement("root");

And to add an attribute to that element:

root.Add(new XAttribute(“AttributeName”, “TheValue”));

Which produces the result: <root AttributeName=”TheValue” />

If you look at the intellisense for XElement constructor you’ll see that none of the 5 overloads takes a string. The nearest is an XName. This is because there is an implicit conversion happening between a string and an XName so that creating XElements does not have to be so arduous. It would be quite irritating to have to declare XElement objects like this:

XElement root = new XElement(XName.Get("root"));

At this point you’ll find that all the VB developers will be gloating because VB9 contains a feature called XML Literals whereby the developer can just write XML directly into the source code file and VB will parse and compile it correctly. An incredibly handy feature I’m sure you’ll agree. But, since I’m a C# developer that’s what I’ll stick with – especially considering that the majority of demos of LINQ to XML I’ve seen are VB based.

If you look closely at XName’s Get method you’ll see that there are two overrides, one for an expanded name, and the other for a local name and a namespace name. The expanded name is just a string of the name with the namespace embedded in the string inside curly braces, like this:

XName.Get("{mynamespace}root");

If you prefer you can use the other overloaded version and provide two strings. The equivalent XName in that case would be created like this:

XName.Get("root", "mynamespace");

Now, you are probably wondering why a static method is being used rather than a constructor. This is because the XML classes are clever enough to reuse existing XName objects. If you create a second XName object with the same characteristics as an existing XName object it will just reuse the existing XName. For example, the following code will output “True” to the console:

XName name1 = XName.Get("{ns}MyName");
XName name2 = XName.Get("MyName", "ns");
Console.WriteLine(object.ReferenceEquals(name1, name2));

XName is immutable (it cannot change) so this is a perfectly acceptable thing to do.

The extended name notation also works if you are using strings while constructing your XElement. For example:

XElement root = new XElement("{mynamespace}root");

However, there is another way of applying namespaces in an XElement. You can use an XNamespace object and add it to the string. Like this:

XNamespace ns = XNamespace.Get("mynamespace");
XElement root = new XElement(ns + "root");

As you can probably tell the + operator has been overloaded so it can be used to add a namespace to a string to produce an XName.

Technorati Tags: ,,,,,

Mixins in C# 3.0

This is something I’ve been mulling around in my head for a few days now. “Out of the box” C# 3.0 does not support mixins, but I think you can get some of the abilities of a mixin with what is there already.

Firstly I should probably explain what a mixin is. A mixin is a class that provides some specific functionality that is to be inherited by a derived class, but it does not have a specialisation (kind-of) relationship with the derived class.

The example that I have is of a class hierarchy representing different types of animal.The base class is Animal, derived from that is Avian and Mammal. Derived from Avian is Parrot, Penguin and Chicken. Derived from Mammal is Dog, Cat, Whale and Bat.

Class-Diagram-1

These animals all have various methods of locomotion. Some can swim, some can run and others can fly. However, as you can see there is no obvious relationship through the base class. It might seem at first glance while designing the class hierarchy that an avian should be able to fly. It is, after all, the first thing that springs to mind when thinking about how birds get from one place to another. But what about flightless birds such as the Dodo? Similarly, don’t all mammals run? No, there are many that live in the sea.

As you can see, adding methods for flight on the Avian base class or running on the Mammal base class don’t work in all cases. This is where mixins come into play.

Mixins can, in this example, provide the functionality for flight, running or swimming, or any other form of locomotion by having the appropriate class inherit the functionality. However, C# does not permit multiple inheritance. You can inherit from one base class only in C#.

But, you can implement multiple interfaces. At this point you are probably thinking “Ah-hah! But interfaces don’t have any functionality”. True, you won’t get too far if you just use some interfaces on the classes. But it is the first step.

Class-Diagram-2

With C# 3.0 came the introduction of Extension Methods and they can be applied, not only to classes but, also, to interfaces. Extension Methods provide additional functionality on an existing class without modifying the class. (You can read more about Extension Methods here). It then becomes possible to create a static helper class for specific functionality that defines the extension methods. Because the classes implement the interface (even if the actual interface doesn’t contain any methods or properties to implement) it will pick up all the extension methods also.

public  static  class SwimMixin
{
    public static void Swim(this ISwim target)
    {
        // Perform Swim functionality on the target
    }
}

This provides very limited mixin functionality. The imitation mixin cannot hold any data of its own which means that so long as the imitation mixin can get away without adding attribute information of its own then it is still useful.

If you need to have the mixin hold its own data then I can, at present, see a number of potential solutions to this problem. Unfortunately no solution is terribly elegant, nor are they problem free.

The first is to use a lookup keyed on weak references to the actual instantiated class with the result of the lookup returning the data needed for the Mixin. The reason for the weak reference is to ensure that the instances of the class get cleared out and are not retained by the imitation mixin. Remember the imitation mixin is built out of a static class so it won’t go out of scope and get cleared up by the garbage collector and everything it holds will stay around as long as the application is running. The main problem with this approach is that as the number of actual instantiated classes increases the lookups get larger and will naturally slow down. Also, some mechanism for clearing out the keys and data that are no longer required has to be implemented as the actual objects are garbage collected.

The second is to use the interface that the extension method is using to provide a method that can be used by the imitation mixin to access its data. This would mean that the actual  instance of the class would have to hold onto some additional data on behalf of the imitation mixin, which negates part of its usefulness.

The third is to create a base class for that all classes that may wish to use a mixin inherit from. This base class can contain “instance” data, in a hashtable keyed on the mixin type (for instance) on behalf of the mixin itself. This would, unfortunately, mean that the data is exposed and render encapsulation useless. It also causes a small hit each time a mixin method needs access to its “instance” data. Naturally, if you are inheriting from an existing framework class you won’t have the option of putting in a base class to hold the mixin data.

Class-Diagram-3

It isn’t too hard to see that it may be possible in the future to have mixin behaviour built directly into the language as we are already part of the way there. In the meantime some limited functionality is available which can be extended to include instance data for the mixin itself with some extra work, but it isn’t without its problems.

Object Initialisers III

It seems that now I’ve got Lutz Roeder’s Reflector on the case with Orcas the way object initialisers work slightly different to how I expected.

As it was described to me as instantiating the object followed by the property calls. However, the compiler has taken some extra steps in there – no doubt on the grounds of safety.

First consider the following code:

// Create Robert Burns, DoB 25/Jan/1759
Person robertBurns = new Person { FirstName = "Robert", Surname = "Burns", 
DateOfBirth = new DateTime(1759, 1, 25) }; Console.WriteLine("{0}", robertBurns);

As I understood the feature, the compiler should have generated code that looked like this:

Person robertBurns = new Person();
robertBurns.FirstName = "Robert";
robertBurns.Surname = "Burns";
robertBurns.DateOfBirth = new DateTime(1759, 1, 25);

However, Reflector reveals that what is actually being produced is this:

    Person <>g__initLocal0 = new Person();
    <>g__initLocal0.FirstName = "Robert";
    <>g__initLocal0.Surname = "Burns";
    <>g__initLocal0.DateOfBirth = new DateTime(0x6df, 1, 0x19);
    Person robertBurns = <>g__initLocal0;
    Console.WriteLine("{0}", robertBurns);

This actually makes some sense. For example, if my new Person object was assigned to a property of something else, or passed in as a parameter to a method it wouldn’t have the opportunity to assign values to the properties on the new object. So, it constructs it all in the background then assigns it to whatever needs it, whether that is a local variable, a property on some object a parameter in a method.

For example, if the above program is reduced to just one line of code:

// Create Robert Burns, DoB 25/Jan/1759
Console.WriteLine("{0}", new Person { FirstName = "Robert", Surname = "Burns",
                                      DateOfBirth = new DateTime(1759, 1, 25) });

The compiled result will be:

    Person <>g__initLocal0 = new Person();
    <>g__initLocal0.FirstName = "Robert";
    <>g__initLocal0.Surname = "Burns";
    <>g__initLocal0.DateOfBirth = new DateTime(0x6df, 1, 0x19);
    Console.WriteLine("{0}", <>g__initLocal0);

Related Posts: Object Intialisers I and II

NOTE: This page was rescued from the Google Cache. The original date was Tuesday, 13th March, 2007

Object Initialisers II

Following on from Gary Short‘s message from my previous post on Object Initialisers, I decided to take a screenshot of Orcas displaying the tooltips.

Screenshot of intellisense showing object initialisers in Orcas

I really have to compliment those that designed and wrote intellisense. Not only does it work with object initialisers, but it is intelligent enough to remove properties that have already be used.

NOTE: This post was rescued from the Google Cache. The original date was Sunday, 11th March 2007.

Object Initialisers I

Continuing with the language enhancements in C#3.0. This post presents the concept of object initailisation.

Say you have a class with a default constructor and lots of properties and you want to be able in initialise the object in one line but the class doesn’t support it. What you can do is use object initailisers:

So, a series of calls like this in C#2.0:

Policy p = new InsurancePolicy();
p.Id = 123;
p.GrossPremium = 100;
p.IptAmount = 10;

Could now be written as this in C#3.0:

InsurancePolicy p = new InsurancePolicy {Id = 123, GrossPremium = 100, IptAmount = 10};

You’ve probably seen something similar already with respect to declaring attributes on an assembly, class or method.

Again, like the other language features in C#3.0, this is just syntactic sugar. The compiler will output the calls in a similar way to the first (C# 2.0) example.

At the moment I can’t see this feature being useful for classes that I build myself as I have control over the class’s constructors and if needed then I can accommodate the parameters as appropriate. Also, the idea of having a single line of code with so many object initialisers in it would seem to me to be a potential source of some really ugly code.

That isn’t to say this isn’t useful for my own classes – it could be used as a way of reducing the need to provide many overloaded versions of the constructor. It would no longer be necessary to anticipate every permutation and combination of properties that are needed to initialise the object past a basic valid state. It could save quite a bit of time. However, caution would need to be exercised. Any constructor created would still need to ensure that the object was created into a valid state. Using object initialisers to initialise the object completely from scratch may not be appropriate.

Object initialisers are a tool. So long as the developer remembers to use the right tool for the right job then this new language feature can be used very effectively.

What object initialisers would be most useful for, as far as I can see, would be for existing classes where I don’t have control over their makeup. e.g. Framework classes, or classes from a third party.

NOTE: This post was rescued from the Google Cache. The original date was Saturday 10th March, 2007.


Original comments:

My first thought when seeing this code was, how will this work with Intelisense?

3/10/2007 6:54 PM | Gary Short

The demonstration that I saw at the MSDN roadshow in Glasgow earlier this week shows that it works.

I would guess that because it knows what object you are instantiating as it comes directly after the new keyword it will be able to determine what public properties with setters are available.

3/10/2007 7:05 PM | Colin Angus Mackay

Cool, thanks for the info Colin!

3/10/2007 7:09 PM | Gary Short

Yep – with the March CTP intellisense for object initialization works great.

Hope this helps,

Scott

3/10/2007 11:33 PM | scottgu

A start on LINQ

I was at the Microsoft MSDN Roadshow today and I got to see some of the latest technologies being demonstrated for the first time and I’m impressed.

Daniel Moth’s presentation on the Language Enhancements and LINQ was exceptional – It really made me want to be able to use that technology now.

What was interesting was that the new enhancements don’t require a new version of the CLR to be installed. It still uses the Version 2.0 CLR. It works by adding additional stuff to the .NET Framework (this is .NET Framework 3.5) and through a new compiler (the C# 3.0 compiler). The C# 3.0 compiler produces IL that runs against CLR 2.0. In essence, the new language enhancements are compiler tricks, which is why the CLR doesn’t need to be upgraded. Confused yet?

Now that the version numbers of the various components are diverging it is going to make things slightly more complex. So here is a handy cheat sheet:

2002 2003 2005 2006 2007ish
Tool VS.NET 2002 VS.NET 2003 VS 2005 VS 2005
+ Extension
“Orcas”
Language (C#) v1.0 v1.1 v2.0 v2.0 v3.0
Framework v1.0 v1.1 v2.0 v3.0 v3.5
Engine (CLR) v1.0 v1.1 v2.0 v2.0 v2.0

The rest of Daniel’s talk was incredibly densely packed with information. Suffice to say, at the moment, LINQ is going to provide some excellent and powerful features, however, it will also make it very easy to produce code that is very inefficient if wielded without understanding the consequences. The same can be said of just about any language construct, but LINQ does do a remarkable amount in the background.

After the session I was speaking with Daniel and we discussed the power of the feature and he said that, since C#3.0 produces IL2.0 it is possible to use existing tools, such as Lutz Roeder’s Reflector, to see exactly what is happening under the hood. An examination of that will yield a better understanding of how LINQ code is compiler.

LINQ code looks similar to SQL. For example:

var result =
    from p in Process.GetProcesses()
    where p.Threads.Count > 6
    orderby p.ProcessName descending
    select p

This allows the developer to write set based operations in C# a lot more easily than before. A rough equivalent in C# 2.0 to do the same thing would probably look something like this:

List<Process> result = new List<Process>();
foreach(Process p in Process.GetProcesses)
{
    if (p.Threads.Count > 6)
        result.Add(p);
}
result.Sort(new DescendingProcessNameComparer());

* NOTE: Assumes that DescendingProcessNameComparer is an existing comparer that compares two Process objects by their name in descending order.

C# 3.0 introduces the var keyword. This is unlike var in javascript or VB. It is not a variant type. It is strongly typed and the compiler will complain if it is used incorrectly. For example:

var i = 5;
i = "five"; // This will produce a compiler error because i is an integer

In short this was only a fraction of what I learned from just one session – I’ll continue the update as I can.

Tags:

NOTE: This post was rescued from the Google Cache. The original date was Monday, 5th March 2007.


Original comments:

Glad you enjoyed it Colin 🙂

Be sure to check out the written version of my talk on my blog!

3/6/2007 11:34 AM | Daniel Moth

Automatic Properties

Continuing my look at the new features found in the C# 3.0 compiler I will look at Automatic Properties.

public class Employee{    public string FirstName { get; set; }
    public string Surname { get; set; }
    public DateTime DateOfBirth { get; set; }
    public Employee Manager { get; set; }}

At first look this might seem more like a definition for an interface, but for the class keyword and the member visibility modifiers.

However, this is actually a new feature where by the compiler will automatically fill in the member fields. This is useful for situations where nothing needs to be done when getting or setting values from the member fields. It means they can be constructed much more quickly as there is no need for tedious creating of private member fields then the public properties. All that is needed is one simple construct.

It is also possible to reduce the visibility of the getter and setter independently. For example, in the above example you may wish to make DateOfBirth to be effectively read-only for all by the class that owns it. You can prefix the set keyword with the private visibility modifier.

But what is the compiler actually producing? The following is the output from Lutz Roeder’s Reflector for the DateOfBirth property:

[CompilerGenerated]
private DateTime <>k__AutomaticallyGeneratedPropertyField2;

public DateTime DateOfBirth
{
    [CompilerGenerated]
    get
    {
        return this.<>k__AutomaticallyGeneratedPropertyField2;
    }
    private [CompilerGenerated]
    set
    {
        this.<>k__AutomaticallyGeneratedPropertyField2 = value;
    }
}

In the code, only the  property is accessible. Attempting to use the compiler generated name produces a compiler error.

If the full name (as shown above) is used then the compiler will complain with three errors:

Compiler errors
# Error File Row Col Project
1 Identifier expected ConsoleApplication2Employee.cs 20 18 ConsoleApplication2
2 Invalid expression term ‘>’ ConsoleApplication2Employee.cs 20 19 ConsoleApplication2
3 ; expected ConsoleApplication2Employee.cs 20 20 ConsoleApplication2

If the <> are removed the message changes to

Compiler errors
# Error File Row Col Project
1 ‘ConsoleApplication2.Employee’ does not contain a definition for ‘k__AutomaticallyGeneratedPropertyField2’ and no extension method ‘k__AutomaticallyGeneratedPropertyField2’ accepting a first argument of type ‘ConsoleApplication2.Employee’ could be found (are you missing a using directive or an assembly reference?) ConsoleApplication2Employee.cs 20 18 ConsoleApplication2

So, why go to all this trouble? Surely it isn’t just to save a few key strokes?

Part of the answer can be seen in a post I made in November 2005: Why make fields in a class private, why not just make them public? and there was a follow up in June 2006 when I returned to The Public Fields Debate Again.

In short, public fields and public properties, although they appear to look identical to the outside in C# are sytactically different once compiled. Automatic Properties are a way to address that. If you, at some point in the future, decide that you need the property to do more then the external interface of the object won’t change, you just turn the automatic property into a normal property/field combination again.

NOTE: This post was rescued from the Google Cache. The original date was Tuesday, 13th March, 2007.

Extensions Methods

I’ve been looking at more of the language enhancements in C# 3.0. In this post I’m going to look at Extensions.

There have been many times went a class has needed to be extended, but the additional code just doesn’t sit right on the class itself. In that case a utility or helper class is created to help carry out these mundane tasks without impacting the main class the helper operates on. It may be because the method requires access to classes that would tightly couple the main class to others.

It is important to remember that the extension method, like any method on a helper or utility class, cannot access the private or protected members of the class it is helping.

For example, take the children’s game Fizz-Buzz which seems to be undergoing a resurgence at the moment. The rules for the method are simple. The program counts from 1 to 100 replacing any value that is divisible by 3 with Fizz and any value that is divisible by 5 with Buzz. If a value happens to be divisible by both 3 and 5 then the output is FizzBuzz. For any other value the number is output.

First here is the version without the extensions:

public static class FizzBuzzHelper
{
    public static string FizzBuzz(int number)
    {
        if ((number % 5) == 0)
        {
            if ((number % 3) == 0)
                return "FizzBuzz";
            return "Buzz";
        }
        if ((number % 3) == 0)
        {
            return "Fizz";
        }
        return number.ToString();
    }
}

class Program
{
    static void Main(string[] args)
    {
        for (int i = 1; i <= 100; i++)
        {
            Console.WriteLine(FizzBuzzHelper.FizzBuzz(i));
        }
        Console.ReadLine();
    }
}

And now the version with the extensions:

public static class FizzBuzzHelper
{
    public static string FizzBuzz(this int number)
    {
        if ((number % 5) == 0)
        {
            if ((number % 3) == 0)
                return "FizzBuzz";
            return "Buzz";
        }
        if ((number % 3) == 0)
        {
            return "Fizz";
        }
        return number.ToString();
    }
}

class Program
{
    static void Main(string[] args)
    {
        for (int i = 1; i <= 100; i++)
        {
            Console.WriteLine(i.FizzBuzz());
        }
        Console.ReadLine();
    }
}

There aren’t actually that many changes (and the example is somewhat trivial).

First, in the extension method, the this keyword is placed before the parameter. It indicates that the extension will go on the int (or rather the Int32) class.

Second, when the extension method is called there is no reference to the utility class. It is simply called as it it were a method on the class (in this case Int32). Also, note that the parameter is not needed because it is implied by the object on which the extension method is applied.

Lutz Roeder’s reflector is already conversant with extension methods so the compiler trickery cannot be seen in the C# view of the method. However, the IL reveals that deep down it is just making the call as before. The following is the extension version:

L_0007: call string ConsoleApplication3.FizzBuzzHelper::FizzBuzz(int32)
L_000c: call void [mscorlib]System.Console::WriteLine(string)

And this is the old-style helper method call:

L_0007: call string ConsoleApplication3.FizzBuzzHelper::FizzBuzz(int32)
L_000c: call void [mscorlib]System.Console::WriteLine(string)

They are identical. So, how does the compiler tell what it needs to be doing?

The method header for the regular helper method:

.method public hidebysig static string FizzBuzz(int32 number) cil managed
{

The method header for the extension method:

.method public hidebysig static string FizzBuzz(int32 number) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor()

And that’s it. C# just hides the need for the ExtensionAttribute. In VB the attribute needs to be explicitly declared on the method.

Intellisense also helps out with extensions. Each extension method appears in the intellisense on the object it is extending. To ensure that the developer is aware that it is an extension the icon in the list has a blue arrow and the tool tip is prefixed with “(extension)”

orcas-extensions-intellisense

It is also possible to create extension methods that take more than one parameter. For example:

public static class PasswordHashHelper
{
    public static byte[] HashPassword(this string password, byte[] salt)
    {
        // Implementation here
    }
}

It is important to note that the this modifier can only be placed on the first parameter. To do otherwise would generate the compiler error “Method ‘{method name}’ has a parameter modifier ‘this’ which is not on the first parameter”

The above multi parameter extension method can then be used like this:

byte[] hashedPassword = plainTextPassword.HashPassword(salt);

NOTE: This entry was rescued from the Google Cache. The original date was Thursday, 15th March, 2007.

Anonymous Types

Anonymous Types are another new feature to the C# 3.0 compiler.

To create one, just supply the new keyword without a class name, followed by the, also new, object initialiser notation.

As the type name is not known it needs to be assigned to a variable declared with the local variable type inference, var, keyword.

For example:

var anonType = new { FirstName = "Colin", MiddleName = "Angus", Surname = "Mackay" };

It is possible to assign a new object to the variable, but it must be created with the object initialisers in exactly the same order. If, say, the following is attempted a compiler error will be generated:

anonType = new {Surname = "Rowling",  FirstName = "Joanna", MiddleName = "Kathleen" };

The corresponding compiler error is: Cannot implicitly convert type ‘anonymous type […ProjectsConsoleApplication4ConsoleApplication4PropertiesAssemblyInfo.cs]’ to ‘anonymous type […ProjectsConsoleApplication4ConsoleApplication4PropertiesAssemblyInfo.cs]’

At the moment I’m not entirely sure where AssemblyInfo.cs comes in. If anyone knows the answer I’d love to know.

Back to the original example. What does this look like under the microscope of Lutz Roeder’s Reflector?

var <>g__initLocal0 = new <>f__AnonymousType0();
<>g__initLocal0.FirstName = "Colin";
<>g__initLocal0.MiddleName = "Angus";
<>g__initLocal0.Surname = "Mackay";
var anonType = <>g__initLocal0;

But that isn’t all that was generated. The compiler also generated the following internal class (Note: Some of the detail has been stripped for clarity)

internal sealed class <>f__AnonymousType0<<>j__AnonymousTypeTypeParameter1,
    <>j__AnonymousTypeTypeParameter2, <>j__AnonymousTypeTypeParameter3>
{
    // Fields
    private <>j__AnonymousTypeTypeParameter1 <>i__AnonymousTypeField4;
    private <>j__AnonymousTypeTypeParameter2 <>i__AnonymousTypeField5;
    private <>j__AnonymousTypeTypeParameter3 <>i__AnonymousTypeField6;

    public <>j__AnonymousTypeTypeParameter1 FirstName
    {
        get
        {
            return this.<>i__AnonymousTypeField4;
        }
        set
        {
            this.<>i__AnonymousTypeField4 = value;
        }
    }

    public <>j__AnonymousTypeTypeParameter2 MiddleName
    {
        get
        {
            return this.<>i__AnonymousTypeField5;
        }
        set
        {
            this.<>i__AnonymousTypeField5 = value;
        }
    }

    public <>j__AnonymousTypeTypeParameter3 Surname
    {
        get
        {
            return this.<>i__AnonymousTypeField6;
        }
        set
        {
            this.<>i__AnonymousTypeField6 = value;
        }
    }
}

Because the developer has no access to the actual type name the an object created as an anonymous type cannot be passed around the program unless it is cast to an object, the base class of all things. It cannot, for obvious reasons, be cast back again. So at this point the only way of accessing the data stored within is via reflection, or with methods already present on object.

Anonymous types can be examined in the debugger quite easily and show us just like any other object.

Debugging anonymous types in Orcas

One especially neat feature of anonymous types is its ability to infer a name when none is given. For example:

DateTime dateOfBirth = new DateTime(1759, 1, 25);
var anonType = new { FirstName = "Robert", Surname = "Burns", dateOfBirth };

The dateOfBirth entry was not explicitly given a name on the anonymous type. However, the compiler inferred a name based on the variable name that was given. The anonymous type therefore looks like this: { FirstName = Robert, Surname = Burns, dateOfBirth = 25/01/1759 00:00:00 }

Naturally, some will dislike this as the anonymous type now has a mix of pascal and camel case for the properties it is exposing.

NOTE: This post was rescued from the Google Cache. The orginal date was Saturday, 17th March, 2007