dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
18.96k stars 4.02k forks source link

NotNullIfNotNull or equivalent support for delegates #74066

Open hugener opened 3 months ago

hugener commented 3 months ago

Brief description:

NotNullIfNotNull is very useful for the example below, but it doesn't work for delegates (non-void).

[return: NotNullIfNotNull("fallback")]
public T? Evaluate(T? fallback)
{
    return ...;
}

However, I would like to do a similar one for delegates:

//// Is there a way to have the compiler check whether what is provided as fallback evaluates to T or T?
//// NotNullIfNotNull refers to the fallback parameter itself and not the result of it.
public T? Evaluate(Func<T?> fallback)
{
    return ...
}

Languages applicable:

C#

Additional information:

The only option now is two add two methods and they cannot be overloads, which could be avoided if NotNullIfNotNull (or similar) would work for delegates public T? EvaluateToOption(Func<T?> fallback) { return ... }

public T Evaluate(Func fallback) { return ... }

Cosifne commented 3 months ago

Redirect this to compiler area to first take a look.