views:

39

answers:

3

If i have an accessor and default property in a base class as follows:

class base{
protected int _foo = 5;
public int foo {get{return _foo;}set{_foo = value;}}
}

Then I derive this class, is it possible to override the default value of _foo?

class derived:base{
// foo still returns 5?
protected new int _foo = 10;
}
+5  A: 

The _foo = 5 statement effectively executes in the base class's constructor. You can add code to the derived class constructor that changes foo's value immediately afterwards:

class derived:base{
    public derived()
    {
        foo = 10;
    }
}
Tim Robinson
A: 

You can create a property:

protected virtual int _foo { get { return 5; } }

and

protected override int _foo { get { return 10; } }
Albin Sunnanbo
it is not a constant. Calling the virtual property in the constructor (eg. to initialize the variable) is not recommended, because of side effects, CA will complain (you call derived code when base class is not initialized).
Stefan Steinegger
That's fine but i cant assign 'foo' anything anymore.
maxp
A: 

You could use a construtor to initialise the derived class and set the base types _foo property:

class derived:base
{
    public derived()
    {
        this._foo = 10;
    }
}
Scott Rickman