Reputation: 35280
Starting with C# 8.0 I can do this:
interface IMyInterface
{
#nullable enable
void DoSomething(string? withValue);
#nullable disable
}
i.e. use the nullable reference type argument string? withValue
, but then when I implement the interface, this is perfectly legal -- in fact when the tool in VS auto-generates the implementation code, this is what results:
class MyImpl : IMyInterface
{
public void DoSomething(string withValue)
{
throw new NotImplementedException();
}
}
I specifically wanted for the implementations to require a nullable reference type for the withValue
argument, so why isn't it required? What is the point of being able to define a nullable reference type argument in an interface?
Upvotes: 3
Views: 1078
Reputation: 70671
why isn't it required?
It's not required because when you compiled the implementation of the interface, you did not enable nullable reference types.
When nullable reference type checking is not enabled, nothing about nullable reference types takes effect. You are explicitly saying that in the context of the code where it's not enabled, you do not want the compiler to provide compile-time enforcement of nullable reference types.
So, it doesn't. It's as if the nullability of the type simply doesn't exist.
What is the point of being able to define a nullable reference type argument in an interface?
For the same reason you can define a nullable reference type argument for any method. To indicate, when nullable reference type checking is enabled, that callers may pass null
as the value for the argument.
That way if and when you compile code that implements or uses that interface in a context where nullable reference type checking is enabled, you will get the expected warning about the types not matching for the implementation. This in turn should make you aware that your implementation stipulates the parameter must be non-null, while in fact it will be possible for code to pass a null value, when calling the member via the interface instead of directly in the implementation.
Note that the warning only happens when the implementation is declared with a non-nullable reference type and the interface is declared with a nullable reference type, because that's the only combination that's dangerous. When the interface is declared with non-nullable and the implementation is declared with nullable, that's perfectly safe and no warning is emitted.
The author of the interface cannot necessarily know whether nullable reference type checking will be enabled when the interface is implemented, or even used. So of course there may be situations where the nullability of the argument isn't important. But when nullable reference type checking is useful, i.e. is enabled, it's every bit as useful as a nullable reference type would be otherwise.
That's the point of being able to define a nullable reference type argument in an interface.
Upvotes: 3