Raphael
Raphael

Reputation: 1040

How to force change a type parameter from a possible nullable type to a guaranteed non-null type

Consider a method like this

public static T WhenNotNull<T, TObject>(this T settings, TObject obj, Func<T, TObject, T> configurator)
{
    return obj != null ? configurator.Invoke(settings, obj) : settings;
}

It's going to be used in a NUKE build project like that

dotnet => dotnet.WhenNotNull(this as IHaveGitVersion, (d, o) => d.SetFileVersion(o.Versioning.AssemblySemFileVer))

It all works great, beside one thing

<Nullable>enable</Nullable>

This will make the analyzer complain about CS8602 Dereference of a possibly null reference for the variable o

SetFileVersion(o.Versioning.AssemblySemFileVer))

I know that I can just suppress it with !. But I would have to do this inside each WhenNotNull() usage.

Or I disable the nullable stuff altogether in the build project.

Is there a way to somehow tell the analyzer that TObject inside the Func<T, TObject, T> won't be null so I don't have to suppress it?

One possible solution I have is using the ? on obj parameter

public static T WhenNotNull<T, TObject>(this T settings, TObject? obj, Func<T, TObject, T> configurator)
{
    return obj != null ? configurator.Invoke(settings, obj) : settings;
}

But I am not sure if there are better solutions for this.

Upvotes: 0

Views: 21

Answers (0)

Related Questions