Difference between Simplified Initialisation and Anonymous Types

Here is a sample code that declares a Person class then uses Simplified Initializations to set its public properties. This code also instantiates an Anonymous Type that has two properties named exactly like the two properties of the Person class.

class Person
{
    public String Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var p = new Person { Name = "Philippe", Age = 27 };
        var q = new { Name = "Johndoe", Age = 88 };

        Console.ReadLine();
    }
}

Initializations of variables p and q looks quite similar. However, under the covers, it is very different.

Let’s look at the generated C# for this, using Reflector:

private static void Main(string[] args)
{
    Person <>g__initLocal0 = new Person();
    <>g__initLocal0.Name = "Philippe";
    <>g__initLocal0.Age = 0x1b;
    Person p = <>g__initLocal0;
    var q = new {
        Name = "Johndoe",
        Age = 0x58
    };
    Console.ReadLine();
}

So, what do we see there?

First, Person’s constructor is invoked (I guess they mean that you d’ont have to invoke it yourself), and that the compiler uses a temporary variable to store this new Person object. Then, the properties set in the simplified initialization are set on that temporary variable, and at last our variable is assigned the reference to the object that is now ready to be used. This is clearly done for atomicity reasons, as the object will not be available while in inconsistent state.

Second, we see that for the anonymous type, it’s pretty much the same as the original code. However, there is no trace of an intermediate variable used during initializations of the object’s properties. Let’s have a look at the code generated for that anonymous type:

[CompilerGenerated, DebuggerDisplay(@"\{ Name = {Name}, Age = {Age} }",
    Type="<Anonymous Type>")]
internal sealed class <>f__AnonymousType0<<Name>j__TPar, <Age>j__TPar>
{
    // Fields
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly <Age>j__TPar <Age>i__Field;
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly <Name>j__TPar <Name>i__Field;

    // Methods
    [DebuggerHidden]
    public <>f__AnonymousType0(<Name>j__TPar Name, <Age>j__TPar Age);
    [DebuggerHidden]
    public override bool Equals(object value);
    [DebuggerHidden]
    public override int GetHashCode();
    [DebuggerHidden]
    public override string ToString();

    // Properties
    public <Age>j__TPar Age { get; }
    public <Name>j__TPar Name { get; }
}

Now, two things to note:

  1. There is no default constructor for that anonymous type, there is only a constructor that takes the values of the two properties.
  2. The two properties are declared as readonly, so they cannot be assigned once the object has be instantiated. In fact, Anonymous Types are immutable.

So, it is quite clear from the generated code that when instantiating an anonymous type, the compiler translates this into a call to the anonymous type’s constructor. It is not shown in Reflector’s C# disassembler, but it can be seen using Reflector’s IL disassembler:

L_001e: ldstr "Johndoe"
L_0023: ldc.i4.s 0x58
L_0025: newobj instance void <>f__AnonymousType0`2<string, int32>::.ctor(!0, !1)

As expected, the call will be to the constructor of the anonymous type.

To sum it up, even if the following two lines look very similar, the reverse call will be very different:

var p = new Person { Name = "Philippe", Age = 27 };
var q = new { Name = "Johndoe", Age = 88 };

For variable p, the specified constructor will be called (in this case, the default one), then properties will be set on the newly created object. For variable q, the generated constructor will be called using properties given as parameters.

"Calling a method on null a reference" by Jon Skeet

Two months ago, I wrote a blog post called Extension Methods and null Objects. In this post, I described how to write Extension Methods in C# 3 and wrote a small sample code to add IsNullOrEmpty as an extension method to the String class. Well, guess what, I found that particular example in a book.

A few weeks ago, I bought Jon Skeet’s book C# in Depth, and have been reading it trough since then (I have to say that it is very well written and a pure joy to read, highly recommended if you are somewhat familiar with C# and would like to polish your knowledge of the language).

Reading part 10.2.4, "Calling a method on a null reference", I was surprised to discover that Jon used exactly the same example as I did! Well, I have to admit that it is I that used the same example as him, as it was already long printed when I wrote that post.

At first it seems odd to be able to call IsNullOrEmpty on a variable that is null without an exception being thrown, particularly if you’re familiar with it as a static method from .NET 2.0. In my view, code using the extension method is more easily understandable. For instance, if you read the expression if (name.IsNullOrEmpty()) out loud, it says exactly what it’s doing.

Nevertheless, I was very pleased with myself and, dare I say it, immediately thought "Great Minds Think Alike" :p.

Something I don’t like about C#

In general, I prefer C# over Java. It’s a matter of personal taste, but I find C# more elegant, even if they are very close to each others. But there is something about C# that always bugs me: the way inheritance is declared.

If we look at this code:

public class FooBar : Bar, Foo
{
}

Apart from Visual Studio’s tooltip that helps you, how do you know if Bar is a interface or a class? It can be both, and there is no way of telling.

We obliviously know that Foo is an interface, as only one base class can be defined and it has to be right after the ":" character (see the Class base specification of the C# language).

A class declaration may include a class-base specification, which defines the direct base class of the class and the interfaces implemented by the class.

class-base:
:   class-type

:   interface-type-list

:   class-type   ,   interface-type-list

interface-type-list:
interface-type

interface-type-list   ,   interface-type

But what about Bar? According to the language specification, it can be either an class or an interface, we cannot know just by looking at it. Guidelines for Names that states that interfaces should be prefixed with I, so we could assume that it is a class. However, in this particular example, Foo is an interface for sure but is not prefixed with I, so we cannot assume that Bar is an interface, right?

Now, if we look at Java’s syntax, it is much neater:

public class FooBar extends Bar implements Foo
{
}

Looking at this, there is no doubt that Bar is a class and Foo is an interface (see Java Language Specification parts on Superclasses and Superinterfaces). Even if the developer gave crappy names, we can sort out what is an interface and what is a class.

Now, that said, Visual Studio will always tell you if it is a class or an interface. but if you open the source file with something else than a smart IDE? Notepad for example? I think that the language should speak for itself and not rely on naming conventions. With C#, you can have a doubt, while with Java there is none.

But I still love C# for everything else, I think…