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:
- Structs cannot have custom default (parameter less) constructors. They however can have other custom constructors. This means that the default constructor can always be called, and that all the fields from the struct will be initialised at there default value;
- Overriding the ToString method is a good idea. It’s always a good idea, even more with a struct as this will prevent boxing of the variable when ToString called.
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:
- When you declare a variable somewhere, without initialising it, the compiler will issue a warning saying that the variable is declared but never used.
- If you try to access one of it’s field, it will issue an error saying that the variable cannot be used because it is unassigned.
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:

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!
Explicit Interface Implementation
In C#, you can explicitly implement interface members in your class or struct. C# language specification explains it better than I can:
For purposes of implementing interfaces, a class or struct may declare explicit interface member implementations. An explicit interface member implementation is a method, property, event, or indexer declaration that references a fully qualified interface member name.
Here’s a small example:
public interface IMyInterface { String SayHello(); } class MyClass : IMyInterface { string IMyInterface.SayHello() { return "Hello from IMyInterface!"; } }
The MyClass explicitly implement the SayHello method from IMyInterface. The interesting thing about explicitly implemented member is that they’re only accessible when accessed trough the interface. From C# language specification again:
It is not possible to access an explicit interface member implementation through its fully qualified name in a method invocation, property access, or indexer access. An explicit interface member implementation can only be accessed through an interface instance, and is in that case referenced simply by its member name.
The below code won’t compile, as the SayHello method is only visible trough the interface:
var o = new MyClass(); Console.WriteLine("MyClass: {0}", o.SayHello());
‘MyClass’ does not contain a definition for ‘SayHello’ and no extension method ‘SayHello’ accepting a first argument of type ‘MyClass’ could be found (are you missing a using directive or an assembly reference?)
Now, let’s add a second method called SayHello with the exact same signature to the class, defined as such:
public string SayHello() { return "Hello from MyClass"; }
This time, the previous code will compile, and will print “Hello from MyClass” in the console.
To access the explicitly implemented method, we have to go trough the interface, calling it as such:
var p = (IMyInterface)o; Console.WriteLine("IMyInterface: {0}", p.SayHello());
This will print “Hello from IMyInterface” in the console, as expected.
The two primary purpose of explicit interface implementation, as described in the C# language specification, are twofold:
- Because explicit interface member implementations are not accessible through class or struct instances, they allow interface implementations to be excluded from the public interface of a class or struct. This is particularly useful when a class or struct implements an internal interface that is of no interest to a consumer of that class or struct.
- Explicit interface member implementations allow disambiguation of interface members with the same signature. Without explicit interface member implementations it would be impossible for a class or struct to have different implementations of interface members with the same signature and return type, as would it be impossible for a class or struct to have any implementation at all of interface members with the same signature but with different return types.
On top of this, a common usage, as described in C# in Depth (2.2.2, page 46), is to palliate the lack of covariant return types (the example is on IClonable interface, see this topic on Stack Overflow).
C# 4.0 and dynamic keyword
With the new dynamic keyword in C# 4.0, a method call on a dynamic object is resolved at runtime. Is is therefore impossible to access the explicitly implemented member on a dynamic object.
dynamic q = new MyClass(); dynamic r = (IMyInterface)q; Console.WriteLine("MyClass: {0}", q.SayHello()); Console.WriteLine("IMyInterface: {0}", r.SayHello());
The above code will print “Hello from MyClass” twice, as SayHello is called on a object who’s runtime type is MyClass. The only way to access IMyIntergace’s SayHello implementation is to cast q or r to IMyInterface before the call:
Console.WriteLine("IMyInterface: {0}", ((IMyInterface) q).SayHello());
Restoring Files From a Complete PC Backup
Today, I was searching for some files that I used to have on my PC, two installs ago (I’m running Window 7 RC now, before that I was running Windows 7 Beta and before that Windows Vista SP1).
However, I apparently missed something when migrating, as I could not find the files. Hopefully, I could find these on the few backups I made before installing the RC. I made backups using Complete PC Backup feature of Windows 7/Vista.
I wondered how to restore only files from an image that was not from this installation. Restore center does not find other installs backup, hence you cannot use it to restore files from another install’s backup files. As I browsed in the backup folder (that is named WindowsImageBackup), I realized that the files stored in there are some .vhd and a bunch of xml files.
I remembered that one of Windows 7 new feature is that you can mount an .vhd file in the disk manager. I never did this before, and it turned out to be piece of cake. Just read here.
Once this was done, I could access all the content of the backed up drives, and restore what I needed.
Sadly, the files were not there, they were on an install I apparently got rid of, so they are lost forever… Now that I have a Windows Home Server at home, I won’t happen again!
