Implicit Conversions in the Atom Library
A few years ago I began building my most polished project to date—the NerdSince1984.Syndication.Atom library. As you may have guessed, it’s a library for representing the Atom Syndication Format, including Feed Paging and Archiving and the Atom Publishing Protocol. The concepts behind the structure of an Atom feed are simple enough, but implementing them as .NET objects is trickier than you may think.
For example, each entry in a feed contains a title represented by an <atom:title> tag, so you could easily expose the Title property of an AtomEntry object as a string, right? Actually, the <atom:title> tag is an atomTextConstruct according to the documentation, which defines it in RelaxNG as:
atomTextConstruct = atomPlainTextConstruct | atomXHTMLTextConstruct
atomPlainTextConstruct =
atomCommonAttributes,
attribute type { "text" | "html" }?,
text
atomXHTMLTextConstruct =
atomCommonAttributes,
attribute type { "xhtml" },
xhtmlDiv
Not just a simple string anymore, is it? In addition to the atomCommonAttributes, the <atom:title> tag can have a type attribute that defines the type of content it contains—plain text, HTML, or XHTML. For a library to fully support the Atom Syndication Format, it must support simple tags like
<atom:title>Implicit Conversions in the Atom Library</atom:title>
and complex tags like
<atom:title xml:lang="fr-CA" custom:generatedby="http://translate.google.com/">
Les conversions implicites dans la bibliothèque Atom
</atom:title>
To accomplish the above, we could employ code à la NerdSince1984.Syndication.Atom like below.
XNamespace custom = "http://example.org/";
AtomEntry frenchEntry = new AtomEntry(...);
frenchEntry.Title = "Les conversions implicites dans la bibliothèque Atom";
frenchEntry.Title.Add(new XAttribute(XNamespace.Xml + "lang", "fr-CA"));
frenchEntry.Title.Add(new XAttribute(custom + "generatedby",
"http://translate.google.com/"));
Notice how we are able to set the Title property as if it expects a string, yet we are also able to call a method on it to add an extension attribute. That's because the Title property is of type AtomTitle, which exposes a from-string implicit conversion operator. Anything that expects an AtomTitle can take a string instead, which gets implicitly converted to an AtomTitle. AtomTitle also derives from AtomTextNode, which exposes a to-string implicit conversion operator, so anything that expects a string can take an AtomTextNode instead.
The NerdSince1984.Syndication.Atom library is replete with implicit conversions, not only for strings, but for DateTime objects and especially XElements. To find out for yourself, download the library in your favorite flavor—3.5 or 4.0.