Using Statement with an “expression”

Reading More Effective C# book, I was amazed to find out that the using statement can be used simply with an expression:

using-statement:
using ( resource-acquisition ) embedded-statement

resource-acquisition:
local-variable-declaration
expression

If the resource-acquisition is an expression, the variable resulting from the expression will be inaccessible to the embedded-statement.

Now, the reason why this is outlined in Bill Wagner’s book is when you write generic classes. Simply put, if expression is something like “a as IDisposable”, if a actually implements IDisposable, it will be disposed after the using statement. If it does not implements IDisposable, nothing will happen.

The beauty of this is that you don’t have to know, it will work in all cases.

I didn’t know that, and I find it very neat!

Getting an Assembly’s Strong name with PowerShell

Quick tip, should get me out of blogging hibernation.

It’s a common issue to find an assembly’s strong name, but this can be done very easily with a simple PowerShell function:

function Get-AssemblyStrongName($assemblyPath)
{
	[System.Reflection.AssemblyName]::GetAssemblyName($assemblyPath).FullName
}

Simply give the assembly’s full path and you’ll get the strong name in return.

Personnaly, I have that in my $profile file and have an alias gan for it.

Why I Love Extension Methods

The other day, I was using for the first time the Html Agility Pack library.

The method I use the most is the SelectNodes to which you give an XPath and that returns an HtlmNodeCollection containing the resulting HtmlNodes or null if no node where found.

I don’t know if this is a design decision, but returning null when there is no match is not very nice. If you use the expression as is in a foreach statement, it will throw a NullReferenceException if no match.

A simple solution is to use the coalescing operator next to the function’s call, in order to give the foreach an empty Enumerable to avoid the exception.

htmlNode.SelectNodes(xpath) ?? Enumerable.Empty<HtmlNode>()

This is working well, but it’s a bit ugly to repeat that in every foreach statement.

This is where Extension Methods are so enjoyable. Let’s just add a new method to our HtmlNode friend that returns an empty enumerable when SelectNodes return null.

internal static class HtmlAgilityPackExtension
{
    internal static IEnumerable<HtmlNode> SelectNodesOrEmpty(this HtmlNode htmlNode, String xpath)
    {
        return htmlNode.SelectNodes(xpath) ?? Enumerable.Empty<HtmlNode>();
    }
}

There we go. From now on, I can simply foreach over a SelectNodesOrEmpty result of any HtmlNode, with no fear of any exception.

Value Types Initialisation

Value Types are a bit special. I won’t go down to the basics, but the differ from Reference Types by holding directly a value instead of a reference.

There are two interesting cases that I’m going to elaborate on. They pretty much make sense, but a little explanation cannot hurt.

Prelude

Here is a very simple struct that I will use to demonstrate my point:

struct DaysAndHours
{
    public int Days { get; private set; }
    public int Hours { get; private set; }

    public override string ToString()
    {
        return String.Format("{0} day(s) and {1} hour(s)", Days, Hours);
    }
}

Notes:

The “unassigned” Value Type

Now, let’s say that I declare a variable of this type, and never assign it. The normal rules of the compiler will apply:

However, if you run the debugger, you can see the variable’s content. If it was a Reference Type, it would be null, but in this case, you can see all that the content is there, with all the fields being at their default value:

StructsInitialisation01

The trick is that, when declaring the variable dh, the instance is allocated on the stack. However, the C# compiler don’t let you do that and wants to make sure you called the new keyword for that value type.

The Backing Field  Issue

In my struct, I lazily used automatically implemented properties that were introduced in C# 3. This leads to a compiler error when using a custom constructor like this one:

public DaysAndHours(int days, int hours)
{
    Days = days;
    Hours = hours;
}

The compiler will report the following error:

Backing field for automatically implemented property ‘DaysAndHours.Days’ must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.

This makes a lot of sense, as the backing fields for these properties have not been initialized. However, we cannot access the backing field, so we cannot initialize the field. Hopefully, the default parameter less constructor will do that, so calling it is sufficient to make sure the backing fields are initialized:

public DaysAndHours(int days, int hours) : this()
{
    Days = days;
    Hours = hours;
}

Conclusion

Always remember that you cannot prevent a struct to be constructed using the default constructor, that has the same visibility as the struct itself. If you are using automatic properties, you have to explicitly call the default constructor in order to initialise the backing fields as you can’t access them directly.

Do You Noda Time?

A few days ago, Jon Skeet announced that he was starting an open source project with a unknown name (that found itself named Noda Time) that aimed to provide a .NET equivalent to Joda Time.

As there were clearly some openings, I proposed to join, and there is now a Google Group for the project. Jon has great expectations for the project itself but also for the methodology. He wants that project to be model:

I want it to be a shining example of how to build, maintain and deploy an open source .NET library.

I’m really eager to see how this will go. I think this is a great opportunity for me to learn a lot of new stuff and meet people.

Next steps for me are to keep up with the ongoing discussions and learn more about Joda Time as I never used it.

I hope I can prove myself useful!

← Previous PageNext Page →