'Nullability of generic type in Action<T>
I have the following code:
public class Maybe<T>
{
private readonly T? _value;
public Maybe(T? value) => _value = value;
public void WhenNotNull(Action<T> func)
{
if (_value != null)
func(_value);
}
}
public class Test
{
void DoSomething<T>(Maybe<T> s)
{
s.WhenNotNull(TestMethod);
}
private void TestMethod<T>([DisallowNull] T x) => Console.WriteLine(x.ToString());
}
Now s.WhenNotNull(TestMethod); generates
warning CS8622: Nullability of reference types in type of parameter '
x' of 'void Test.TestMethod<T>(T x)' doesn't match the target delegate 'Action<T>' (possibly because of nullability attributes)
There is no way for the parameter to be null, is there any way to signal this to the compiler?
NB: If the Maybe object is concrete (eg. Maybe<string>), this warning is not generated.
Solution 1:[1]
The Action<T> delegate is defined as follow:
public delegate void Action<in T>(T obj);
You can define your own delegate which includes the DisallowNull attribute:
public delegate void MyAction<T>([DisallowNull] T x);
If you now change WhenNotNull to use MyAction<T> instead of Action<T>, the warning will be gone.
Solution 2:[2]
Changed the signature of DoSomething to include where T: notnull
public void DoSomething<T>(Maybe<T> s) where T: notnull
Credit to @nbokmans and @Matthew Watson.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Heinzi |
| Solution 2 | Abstractor |
