Skip to content

Expression visitor that applies null conditional member access the same way the C# null propagation operator (?.) does.

License

Notifications You must be signed in to change notification settings

leandromoh/NullPropagationVisitor

Repository files navigation

Nuget Fuget GitHub

NullPropagationVisitor

Expression tree is an amazing feature of C#, however it only supports a limited subset of C# features.
While there is no native support to null propagation operator a?.b, this library can do the job as an expression visitor.
Just call Visit method of the visitor and you are done!

As well the ?. operator, the visitor evaluates its left-hand operand no more than once.
You can use projects like ReadableExpressions to check the expression returned by visitor.

Examples of use

Check some examples of use in unit tests

Transformation

It works from the basic cenarios:

Expression<Func<string, int>> ex = str => str.Length;

which become something like

(string str) =>
{
    string caller = str;

    return (caller == null) ? null : (int?)caller.Length;
}

To the complex ones

Expression<Func<string, char>> ex = str => str == "foo" ? 'X' : Self(str).Length.ToString()[0];

which become something like

(string str) => (str == "foo")
    ? (char?)'X'
    : {
        string caller =
        {
            int? caller =
            {
                string caller = Program.Self(str);

                return (caller == null) ? null : (int?)caller.Length;
            };

            return (caller == null) ? null : ((int)caller).ToString();
        };

        return (caller == null) ? null : (char?)caller[0];
    }

About

Expression visitor that applies null conditional member access the same way the C# null propagation operator (?.) does.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages