1

I don't understand how this compiles and works perfectly :|

Since when is it possible to change the type of a property (from Nullable<bool> to bool and from int to Nullable<int>) when overriding it?

public class Program
{
    public static void Main(string[] args)
    {
        var testBase = new BaseClass();
        var testDerived = new DerivedClass();

        Console.WriteLine("'" + Convert.ToString(testBase.BaseInt) + "'");
        Console.WriteLine("'" + Convert.ToString(testDerived.BaseInt) + "'");

        Console.WriteLine("'" + Convert.ToString(testBase.BaseBoolNullable) + "'");
        Console.WriteLine("'" + Convert.ToString(testDerived.BaseBoolNullable) + "'");
    }
}

public class BaseClass
{
    public bool? BaseBoolNullable { get; set; }
    public int BaseInt { get; set; }
}

public class DerivedClass : BaseClass
{
    public new bool BaseBoolNullable { get; set; }
    public new int? BaseInt { get; set; }
}

Output:

'0'
''
''
'False'
Bruno
  • 4,685
  • 7
  • 54
  • 105

1 Answers1

2

You haven't overridden the base properties though, just hidden them.

If you change DerivedClass like so, to access the base class's properties, you'll see that they're still available.

public new bool BaseBoolNullable
{
    get { return base.BaseBoolNullable ?? false; }
    set { base.BaseBoolNullable = value; }
}
public new int? BaseInt
{
    get { return base.BaseInt; }
    set { base.BaseInt = value ?? 0; }
}

If you used virtual and override then you'd see that, as you expected, you can't actually override a property with a different type.

public class BaseClass
{
    public virtual bool? BaseBoolNullable { get; set; }
    public virtual int BaseInt { get; set; }
}

public class DerivedClass : BaseClass
{
    public override bool BaseBoolNullable { get; set; }
    public override int? BaseInt { get; set; }
}

'DerivedClass.BaseBoolNullable': type must be 'bool?' to match overridden member 'BaseClass.BaseBoolNullable'

'DerivedClass.BaseInt': type must be 'int' to match overridden member 'BaseClass.BaseInt'

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • Is it a big code smell to write such code as in my question? Like morally wrong or something – Bruno May 10 '17 at 23:49
  • your second example won't compile, right? – Bruno May 10 '17 at 23:56
  • 1
    @ibiza I'd say it's a *pretty big indication* of a code smell. There *are* uses for hiding members, but it's almost always a bad idea – Rob May 11 '17 at 00:06