Tuesday, July 7, 2015

Abusing operator overloading for expression building

Sharepoint lists have a built-in SOAP API. In order to query a list, one has to build a query in XML, along the following lines:

<And><Eq><FieldRef Name="ID"/><Value>100</Value></Eq><NotNull><FieldRef Name="Name"/></NotNull></And>

Those strings are hard to follow, and building them is error prone. To the rescue comes operator overloading in C#. The idea is: field names are wrapped in class instances, comparison between those and numbers/strings produces a condition object, AND/OR between those produces compound condition objects, on the final stage you serialize that chain into an XML string.

The only caveat is, C# doesn't allow for && and || overloading, so we have to overload the bitwize operators & and | instead. The precedence is still what one would expect - AND before OR.


With that in place, the expression above can be written like that:

CAMLField f_ID = F("ID"), f_Name = F("Name");
(f_ID == 100 & f_Name.NotNull).ToString();

No comments:

Post a Comment