An open API service indexing awesome lists of open source software.

https://github.com/leandromoh/nullpropagationvisitor

Expression visitor that applies null conditional member access the same way the C# null propagation operator (?.) does.
https://github.com/leandromoh/nullpropagationvisitor

csharp expression expression-tree null-safe visitor

Last synced: 7 months ago
JSON representation

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

Awesome Lists containing this project

README

          

[![Nuget](https://img.shields.io/nuget/v/NullPropagationVisitor?style=plastic)](https://www.nuget.org/packages/NullPropagationVisitor/)
[![Fuget](https://www.fuget.org/packages/NullPropagationVisitor/badge.svg)](https://www.fuget.org/packages/NullPropagationVisitor)
![GitHub](https://img.shields.io/github/license/leandromoh/NullPropagationVisitor)

# NullPropagationVisitor

[Expression tree](https://docs.microsoft.com/dotnet/csharp/programming-guide/concepts/expression-trees/) is an amazing feature of C#, however it only supports a [limited subset of C# features](https://github.com/dotnet/csharplang/discussions/158).
While there is no native support to null propagation operator `a?.b`, this library can do the job as an [expression visitor](https://stackoverflow.com/questions/41432852/why-would-i-want-to-use-an-expressionvisitor).
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](https://github.com/agileobjects/ReadableExpressions) to check the expression returned by visitor.

## Examples of use

Check some examples of use in [unit tests](NullPropagationVisitor.UnitTest/NullPropagationVisitorTest.cs)

## Transformation

It works from the basic cenarios:

```c#
Expression> ex = str => str.Length;
```
which become something like
```c#
(string str) =>
{
string caller = str;

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

To the complex ones
```c#
Expression> ex = str => str == "foo" ? 'X' : Self(str).Length.ToString()[0];
```
which become something like
```c#
(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];
}

```