2

Is there a way to hide a member of the base-class?

class A
{
  public int MyProperty { get; set; }
}

class B : A
{
  private new int MyProperty { get; set; }
}

class C : B
{
  public C()
  {
    //this should be an error
    this.MyProperty = 5;
  }
}
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
  • 5
    No. There is not. [C# ascribes to the LSP](http://en.wikipedia.org/wiki/Liskov_substitution_principle). The best that can be done is to throw an exception; or use more refined Interfaces in some cases. –  May 25 '12 at 02:27
  • @pst: Eric Lippert has made it quite clear to me in several discussions that subtyping in C# does not use the Liskov definition. – Ben Voigt May 25 '12 at 02:43
  • 3
    I'm curious as to why you would ever want to do this. – casablanca May 25 '12 at 02:46
  • @BenVoigt I'd be interested in reading resources on the subject. Whenever I think of the LSP I generally only consider a mild form (e.g. mostly signatures and not necessarily invariants or all the other semantics it covers). –  May 25 '12 at 04:00
  • @casablanca, I'd like to do it since I overrode a base class that offers many methods to override, one of them uses a property, and I ommitted the usage of that property, so I thought about removing it. – Shimmy Weitzhandler May 25 '12 at 08:55
  • @pst: http://blogs.msdn.com/b/ericlippert/archive/2007/10/17/covariance-and-contravariance-in-c-part-two-array-covariance.aspx as well as many of http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/ – Ben Voigt May 25 '12 at 12:24
  • @pst: Also, in a very different way, here: http://blogs.msdn.com/b/ericlippert/archive/2011/09/19/inheritance-and-representation.aspx – Ben Voigt May 25 '12 at 12:26

1 Answers1

1

There is not a means to hide members in the C# language. The closest you can get is to hide the member from the editor, using EditorBrowsableAttribute.

public class B : A
{
    [EditorBrowsable(EditorBrowsableState.Never)]
    new public int MyProperty {
        get;
        set;
    }
}

I would dare say that there is no guaruntee that this will work for other editors than Visual Studio, so you are better off throwing an exception on top of it.

public class B : A
{
    [EditorBrowsable(EditorBrowsableState.Never)]
    public new int MyProperty {
        get {
            throw new System.NotSupportedException();
        }
        set {
            throw new System.NotSupportedException();
        }
    }
}
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
David Anderson
  • 13,558
  • 5
  • 50
  • 76