emile bosch (ツ)

← all writing

Practical use of the operator "explicit" in XLinq

Dec 19, 2005 · 2 min read · #dotnet · #linq · #csharp

Probably everyone knows this already , but i am going to waste some energy on it anyway, as it raises way too many eyebrows lately :) As long as C# exists it supports the type conversion operator “explicit”. Neverheless i’ve never seen any practical use on the operator before. Probably because it has the tendency to release the “Huh?!1?” effect among developers. Until i started working with XLinq for my “Visual Fx” objectbuilder strategy. I wrote this little example to clarify:

public Example(XElement node)
{
    string str = (string)node.Attribute("Name"); //Convert it to a string
    int number = (int)node.Attribute("Number");  //Convert it to an int
}

As you can see here, the Attribute property of type XAttribute can be casted to an String aswel to an Int (and several more types like DateTime, TimeSpan, Guid etc). Which is unusual since these types are not in the inheritence chain of XAttribute. This behaviour is conceived by using the “explicit” operator. By implementing this operator, which is easy, you are responsible for converting the current type to your target type by doing so:

class XAttribute {
  //More really exciting code

  public static explicit operator string(XAttribute a)
  {
      if (a == null)
      {
            return null;
      }
      return a.value;
  }
}

Now this isn’t exactly rocket science or anything but good to know when you encouter this behaviour in your new Xlinq applications. I’ve somewhat mixed feelings on this operator since there is no visual intellisense support for it available, thus there is no way of telling wheter you can simply cast an type using that operator or need to implement your own custom casting. Except for that minor point it certainly eases writing Xlink queries. Also, there is an “implicit” operator which does a similiar thing except you don’t have to write the cast explicitly, thus typing:

string str = node.Attribute("Name")

will suffice. (Note that the XAttribute doesnt implement the “implicit” operator so this won’t compile)

More information on explicit and implicit on msdn: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfexplicit.asp

Recovered from my old bloggingabout.net blog via the Wayback Machine.

enjoyed this? there's 21 years more where that came from

More writing →

← previous

No i'm not dead.. well at least not mentally..

next →

Pimp your winform application with VisualFX Cab ObjectBuilder Extension