The answer to why this code works

Saturday, Jan 23, 2010 2 minute read Tags: generic .net umbraco
Hey, thanks for the interest in this post, but just letting you know that it is over 3 years old, so the content in here may not be accurate.

So at the start of this week I put up a blog asking Why this code works, and to be honest I've grown quite a bit of an ego since then as no-one has been able to answer the question correctly.

One person did get close, but close doesn't quite cut it ;).

Well the answer is actually very simple, and it's a really handy feature of the C# language, explicit operators.
Explicit operators allow you to define explicit casting between types. So the code that was missing from my original post was this:

1.public static explicit operator UmbracoPage(XElement x) {
2.    return new UmbracoPage(x);
3.}

What I've done here is defined how the compiler is to treat a casting of an XElement to an instance of UmbracoPage, and since UmbracoPage inherits IUmbracoPage there is already a defined casting to it.

Inside the body of my explicit operator I can do anything I desire, here I'm just returning a new instance, passing the XElement to the constructor.

I find it really quite elegant, and that it reduces code smell quite nicely.

But explicit operators also have a buddy, in the form of implicit operators (which was the close-but-no-cigar answer). These work by the type being defined by the assignment target, eg:

1.UmbracoPage page = xElement;

I'm personally not a fan of implicit operators though, I find them less obvious when you're reading code.

So there you have it, a slightly obscure language feature to play with!