I have an extension function called TryGetValueAs
which basically combines TryGetValue
with a cast. The problem is that I keep getting nullability warnings and I can't seem to get it right.
I have the following code:
using System.Diagnostics.CodeAnalysis;
public static class Extensions
{
public static bool TryGetValueAs<TOut, TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, [MaybeNullWhen(false)] out TOut value)
where TOut : TValue
{
if (dictionary.TryGetValue(key, out var v))
{
value = (TOut)v!;
return true;
}
else
{
value = default;
return false;
}
}
}
public interface IFoo {}
public class Foo : IFoo {}
class Program
{
public static void Main(string[] args)
{
var dict = new Dictionary<string, IFoo>();
if (dict.TryGetValueAs("foo", out Foo foo))
{
Console.WriteLine(foo.ToString());
}
}
}
I tried changing out Foo foo
to out Foo? foo
, but that only results in more warnings. How can I write this function so that it correctly handles the nullability, while also being compatible with both values and references?