Overriding the default value in a derived class (C #)

If I have the accessor and default property in the base class as follows:

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

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

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

The operator _foo = 5effectively executes in the constructor of the base class. You can add code to the constructor of the derived class, which immediately changes the value foo:

class derived:base{
    public derived()
    {
        foo = 10;
    }
}
+6
source

You can use the constructor to initialize the derived class and set the basic _foo properties:

class derived:base
{
    public derived()
    {
        this._foo = 10;
    }
}
+1
source

:

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

protected override int _foo { get { return 10; } }
0

Source: https://habr.com/ru/post/1760260/


All Articles