There is a DbLinq provider for multiple non MS-SQL databases. The project is open-source and hosted on the Google Projects under MIT license.

It is even more interesting, however, that it contains dynamic expression parser that allows code like this one to execute:

sealed class Order
{
  public double SubTotal { get; set; }
  public double Shipping { get; set; }
}

static void Main()
{
  var calculateTotal = DynamicExpression
    .ParseLambda<Order, double>("SubTotal*@0+Shipping", 0.12)
    .Compile();

  var order = new Order
  {
    SubTotal = 124.99,
    Shipping = 7.99
  };
  Console.WriteLine(calculateTotal(order));
  Console.ReadLine();
}

Output would be:

22,9888

Basically this parser is used to convert the string representation into some sort of Abstract Syntax Tree, that is then used to build .NET Expression.

The parser is quite limited, but it also features:

  • Just 2000 lines of code
  • Ability to call methods or some static classes
  • No need to load the assemblies into the memory

Here’s a nice codeblock, that tells the story about extensibility of this parser:

static Dictionary<string, object> CreateKeywords() 
{
  var d = new Dictionary<string, object>(
    StringComparer.OrdinalIgnoreCase)
  {
    {"true", trueLiteral},
    {"false", falseLiteral},
    {"null", nullLiteral},
    {keywordIt, keywordIt},
    {keywordIif, keywordIif},
    {keywordNew, keywordNew}
  };

  foreach (Type type in predefinedTypes) 
    d.Add(type.Name, type);
  return d;
}

Now, can this parser be used to provide alternative Domain Specific Language for the Validation and Business Rules? Obviously, yes (but probably, later).

Note, that the combination of ExpressionParser + .NET Linq expressions is currently of no match to the Boo.

Yet, it provides really light-weight “build-your-own-compiler” system with the only dependency on .NET.

Additionally, this might be a hint of what future C# compiler extensibility might look like.

By the way, if you are interested in other hidden-jem usages of .NET Linq Expressions – check out How to Find Out Variable or Parameter Name in C#

Posted in C#