I am using C# 8.0 with nullable errors turned on.
I have a method in which the nullable property of the return type is set to something other than null
. Both the return type and its property are going to be used so just returning the property is not an option.
public static T DoSomething<T>() where T : IMyInterface, new()
{
T myObject = new T();
myObject.NullableProperty = "Definitely not null";
return myObject;
}
public interface IMyInterface
{
string? NullableProperty { get; set; }
}
I have no control over IMyInteface
.
Is there a way to inform the consumers of this method that the property is not null
?
The documentation mentions the attributes MemberNotNull
and MemberNotNullWhen
, but these are for the members of the class of the method itself and not for the return value.
I could, of course, simply tell the compiler to forgive the nullability of the property when using the result of the method:
var result = DoSomething<MyImplementation>();
var length = result.NullableProperty!.Length;
but this seems like a hack and would require all consumers of the method to know they could trust the method to not return a property with a null
value.
The other option is to use an out parameter on the method:
public static T DoSomething<T>(out string notNullResult)
where T : IMyInterface, new()
{
T myObject = new T();
myObject.NullableProperty = "Definitely not null";
notNullResult = myObject.NullableProperty;
return myObject;
}
then it could be called as follows:
var result = DoSomething<MyImplementation>(out string notNullResult);
var length = notNullResult.Length;
but that would add extra parameters to the method and adds some confusion (the consumer would ask why can they use notNullResult
but not result.NullableProperty
).