views:

58

answers:

2

I have an abstract base class that has a Property on it that I would like to prevent both hiding, aka new, and override on.

public abstract class DomainObject
{
    public bool IsDeleted { get; set; }
}

public class BankAccount : DomainObject
{
    public bool IsDeleted { get; set; }
}

The issue is: I need BankAccount to inherit from the base DomainObject class, so I can't mark it as sealed, but I want to prevent the situation, an override or new, of IsDeleted at compile time.

+7  A: 

In this case IsDeleted is not virtual so an override is not possible. In general though you can prevent the override case by not making a property virtual in the first place or preventing further overrides by specifying the sealed modifier on the property

public sealed override IsDeleted { get; set; }

However you can't prevent the hidding via new. There is no way to prevent a sub-type from using new on an existing property other than preventing sub-types altogether

JaredPar
@JaredPar thanks for your response, I tried that as well, however, it will not compile and throws a "no suitable method found to override"
Lucas B
@Lucas B, that's because the property in your case is not virtual at all. I was providing an example on how to prevent an override in the case where IsDelete was virtual
JaredPar
Well I never knew 'sealed' could be used in that context.
Paul Ruane
@JaredPar it is not marked virtual, because I want to prevent an override. I tried creating one more level of base class, DomainObjectBase with a public virtual bool IsDeleted, and then changed DomainObject's signature to public sealed override IsDeleted, but that will only prevent an override and not a hide.
Lucas B
@Lucas B you can't prevent a hide, it's just not possible in C#
JaredPar
+2  A: 

Why do you need such feature? It is not possible to prevent neither properties not methods from hiding in subclasses.

Petr Kozelek
+1, because I'm curious what the answer is as well.
Kirk Woll
Agreed. Trying to use a sealed property in an abstract class sounds like a bad idea. Unless I am missing something.
Chandam
We are using some code generation tools that create domain objects that all inherit from a base class. A few of the member fields are identical across all the members and so we created an interface for those fields to be used for generic manipulation of those objects. Thus, in case a field gets added unintentionally during code generation we want the issue to be exposed during compilation. Fortunately, it does generate a warning, but we don't want to set build to fail on warnings...
Lucas B
If I understood you well then for your needs there is nothing wrong if hiding the properties. Since you are using interfaces then correct property of method will be used in your application - that property which is defined in the super class implementing the interface.
Petr Kozelek