2

Bit of a dumb question, but I'm wondering what the accepted way of passing data from back to an overridden base method is in c#.

e.g. I guess I could do:

class A
{
    int x;
    public virtual void DoStuff() {
        Console.WriteLine(x);
    }
}

class B : A
{
    public override void DoStuff() {
        x = 1;
        base.DoStuff();
    }
}

But is there a better method that for example doesn't require the use of a member variable?

UpTheCreek
  • 30,123
  • 33
  • 148
  • 220

4 Answers4

8

One solution can involve the use of a protected method that has an argument to reuse code from the base class.

class A
{
    public virtual void DoStuff() {
        DoStuffInternal(0);
    }
    protected void DoStuffInternal(int x) {
        Console.WriteLine(x);
    }
}

class B : A
{
    public override void DoStuff() {
        DoStuffInternal(1);
    }
}
jdehaan
  • 19,426
  • 6
  • 56
  • 95
2

Why not use a parameter?

class A
{
    public virtual void DoStuff(int x) {
        Console.WriteLine(x);
    }
}

class B : A
{
    public override void DoStuff(int x) {
        //do stuff
        int y = 1
        base.DoStuff(y);
    }
}
Maximilian Mayerl
  • 10,849
  • 1
  • 31
  • 40
2

How about

abstract class A
{
    protected abstract int X { get; }
    public void DoStuff() {
        Console.WriteLine(X);
    }
}

class B : A
{
    protected override int X { get { return 1; } }
}
Mark Heath
  • 46,816
  • 28
  • 132
  • 191
0

You may use something like Template Method design pattern:

class A
{

    public void DoStuff() {
        var x = DoGetX();
        Console.WriteLine(x);
    }

    protected abstract int DoGetX();
}

class B : A
{
    protected override int DoGetX() {
      return 1;
    }
}

For almost every developer property is looks like simple wrapper around field, and we know that there are no such thing like virtual fields. So I think that abstract method is much more preferable solution in this case(we already discussed differences between properties and methods here).

Community
  • 1
  • 1
Sergey Teplyakov
  • 11,107
  • 32
  • 47