Is this hiding behavior as intended? #7217
-
I'd like to have classes with variants in which some properties can be null, and variants where they can't be null. I have been playing around with the "new" keyword to hide a nullable version of a property and provide a new one that cannot be null. When overriding a base class that has this property as nullable with a "new" property that cannot be null, leads to null value of the orginal property. This is demonstrated by class D in the following example. When I create an instance of that class, the Value parameter is set. When assigning that variable to a variable of the type I1 (where the Value property is nullable), then the Value is null. However, when I introduce an interface I2, which hides the nullable property Value of I1 and implement that interface in class C, the Value property of an instance of C always has a not null value, even when addressed as an I1. I am pleased that I can create nullable and not nullable variants of classes this way, but I am not sure if this is the intended behavior of C#. I'd like to use this pattern, but only if there is a guarantee that a future version of C# still behaves the way it is doing now. BTW. this works identical under net7.0 and net8.0.
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 15 replies
-
When you want to have things but not needing them it's where you can save yourself a lot of troubles.
This probably wouldn't break in future releases but really not something you want to use as a pattern, imo you're making something extremely simple relatively complicated, the Another point is you're making hierarchies or design your code solely based on whether something is nullable, your making something that should trivial to decide a relatively hard choice. If you need to support both nullable and non-nullable members you can just define your interface like this: public interface I1
{
string Value {get;}
string? GetValueOrDefault();
} Just to show you another example/alternative is doing something like this: public interface I1
{
string? Value {get;}
public string GetValueOrEmpty()
=> Value is null ? string.Empty : Value;
} Hope it helps. |
Beta Was this translation helpful? Give feedback.
The hiding works as we intended it to based on just how hiding works in the language since v1. Your use case in terms of how you use it is not something i would personally recommend. There's no connection between the fact that it works for you, and the idea that it's a good idea.