views:

341

answers:

3

I have an abstract class with an abstract property that is set to have both Get and Set. I know I'll always want to be able to get this property from derived classes but there are some cases where it doesn't make sense to set this property in certain types of derived classes.

I can't just omit the Set accessor in a derived class (see code example below). I could override the set accessor in a derived classes to do nothing with the values passed by the user. But is there another way that actually make the property in a specific derived class read only? Ultimately I'm displaying these properties in a property grid and I don't want the user to be entering values into a field that is going to do nothing. Maybe I just attribute the property as read only in specific derived classes?

Also I'd really really rather not mess with any of the type descriptor stuff to get properties to display correctly in a property grid, such as overriding ICustomTypeDescriptor.

public abstract class MyClass
{
    public abstract string MyProperty
    {
        get;
        set;
    }
}

public abstract class MyDerivedClass
{
    public override string MyProperty
    {
        //VS complains that the Set accessor is missing
        get;
    }
}
+2  A: 

You should not do this. What you are saying by defining your getter and setter in the abstract class is "you must implement this if you want to inherit from me." Then you are asking, "how can I made a derived class ignore this rule."

The answer is that if you have a situation that every derived class needs a getter, put that in the abstract class and let the derived class decide if they will implement a setter or not by leaving it out of the abstract class.

Or alternatively, you can create two more classes that derive from the initial abstract class, one that implement the setter and one that does not and then have your derived class generalize the one of those that makes sense, but that is overkill I think.

JP Alioto
If you leave setter out of the abstract class, derived class will not be able to override the property and add the setter.
nightcoder
@nightcoder: Yes, you're right, it would need to be virutal and not abstract.
JP Alioto
A: 

You should use abstract not override:

public abstract class MyClass
{
    pubic abstract string MyProperty
    {
        get;
        set;
    }
}

public abstract class MyDerivedClass
{
    pubic abstract string MyProperty
    {
        get;
    }
}

but ike @JP wrote, you shouldn't do this.

dario-g
A: 

look like you searching for [ReadOnly(true)] attribute this will show to property grid your property, as readonly.
but in your class you can use it as usual property (with read and write possibilities)

Avram