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.
- Host: GitHub
- URL: https://github.com/leandromoh/nullpropagationvisitor
- Owner: leandromoh
- License: mit
- Created: 2021-05-15T04:53:04.000Z (almost 5 years ago)
- Default Branch: main
- Last Pushed: 2021-05-21T01:34:31.000Z (almost 5 years ago)
- Last Synced: 2025-07-03T02:05:43.235Z (10 months ago)
- Topics: csharp, expression, expression-tree, null-safe, visitor
- Language: C#
- Homepage:
- Size: 26.4 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
[](https://www.nuget.org/packages/NullPropagationVisitor/)
[](https://www.fuget.org/packages/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];
}
```