C# Extension Functions: Full Interface

The full API for integrated .NET extension functions is available via the .NET classes ExtensionFunctionDefinition and ExtensionFunctionCall, both defined in the Saxon.Api module. Here is a worked example that defines an extension function to calculate square roots, registers this extension function with the Processor, and then invokes it from an XPath expression:

public class Sqrt : ExtensionFunctionDefinition { public override QName FunctionName => new QName("http://math.com/", "sqrt"); public override int MinimumNumberOfArguments => 1; public override int MaximumNumberOfArguments => 1; public override XdmSequenceType[] ArgumentTypes => new XdmSequenceType[] { new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?') }; public override XdmSequenceType ResultType(XdmSequenceType[] ArgumentTypes) { return new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?'); } public override bool TrustResultType => true; public override ExtensionFunctionCall MakeFunctionCall() { return new SqrtCall(); } } public class SqrtCall : ExtensionFunctionCall { public override XdmValue Call(XdmValue[] arguments, DynamicContext context) { bool exists = arguments[0].Any; if (exists) { XdmAtomicValue arg = (XdmAtomicValue)arguments[0][0]; double val = (double)arg.Value; double sqrt = System.Math.Sqrt(val); return new XdmAtomicValue(sqrt); } else { return XdmEmptySequence.Instance; } } } Processor proc = new Processor(); proc.RegisterExtensionFunction(new Sqrt()); XPathCompiler xpc = proc.NewXPathCompiler(); xpc.DeclareNamespace("mf", "http://math.com/"); XdmItem result = xpc.EvaluateSingle("mf:sqrt(2)", null); Console.WriteLine("Square root of 2 is " + result);

Full details of the interface are defined in the API documentation for class ExtensionFunctionDefinition.