Considering the following class:
public class Property
{
public string StringValue { get; private set; }
private Property(string value)
{
this.StringValue = value;
}
}
I am trying to write a TrySomething method (with nullable enabled). I first wrote something like that:
public bool TryGetValue<T>([NotNullWhen(true)] out T? value)
{
value = JsonSerializer.Deserialize<T>(this.StringValue);
return value != null;
}
When using such implementation with reference type, I get the CS8602 warning when writing the following code:
if (property.TryGetValue<Foo>(out var v))
{
v.ToString(); // OK
}
else
{
v.ToString(); // CS8602
}
But when writing it with value types, it does not:
if (property.TryGetValue<int>(out var v))
{
v.ToString(); // OK
}
else
{
v.ToString(); // OK
}
Is it possible to write such methods for value types?
vbenullafterint.TryParse(s, out var v)?intis a valuetype that cannot be null. So in the implementation ofint.TryParse(and probably most of all thoseTrySomething<T>(out v)) there is some assigment likev = default(T). And in case ofint, thedefault(int)is0and notnull. So of course there is no CS8602, for variables of a value-typebool TrySomething(...)method, you should ensure it doesn't throw an exception. Never! Because that's be basic expection of anyone using such aTry...Only the boolean result should indicate whether the operation was successful or not. That's not the case for yourTryGetValue, because JSON deserialization will throw an exception on an invalid JSON stringint.TryParseis indeed unrelevent. But still the implementation for value types does not trigger the warning (especially the first one).nullunless you explicitly specify them to be nullablebool TryGetValue<T>([NotNullWhen(true)] out T? value)