Chielt
Chielt

Reputation: 212

Base constructor in base class instead of derived class in C#

I'm learning how to properly apply OO principles in C#. I came across a little problem and I can't figure out how to solve it. I run into the following problem:

The current situation:

public abstract class Foo
{
    protected Foo()
    {
        //does nothing
    }
}

public class Bar : Foo
{
    public BarX ( int a, int b, int c) : base()
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public doStuff()
    {
        //does stuff
    }
}

public class BarY : Foo
{
    public Bar( int a, int b, int c) : base()
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public doStuff()
    {
        //does stuff
    }
}

The point is that I hafe different types of Foo. In this case it would be circles and rectangles. I want them to have the same constructors as each type has the same attributes. They only have a different doStuff() method. I have tried many combinations but every time I try to move the arguments to the base class's constructor it tells me that 'some class does not contain a constructor that takes 0 arguments' (or 3 arguments) depending how I move around my code.

My question is how I can move the assignment of a, b and c's values to the abstract class's constructor?

Upvotes: 1

Views: 111

Answers (2)

Dave New
Dave New

Reputation: 40092

That's because BarY and BarX are calling a default constructor (base()) which doesn't exist in your base class when you only have a parameterised constructor. You need to pass the arguments through as well (base(a, b, c)):

public abstract class Foo
{
    protected Foo(int a, int b, int c) 
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public abstract void doStuff();
}

public class Bar : Foo
{
    public BarX (int a, int b, int c) : base(a, b, c)
    {

    }

    public override void doStuff()
    {
        //does stuff
    }
}

public class BarY : Foo
{
    public Bar(int a, int b, int c) : base(a, b, c)
    {

    }

    public override void doStuff()
    {
        //does stuff
    }
}

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

The following will work:

public abstract class Foo
{
    protected Foo(int a, int b, int c)
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public abstract void doStuff();
}

public class Bar : Foo
{
    public Bar(int a, int b, int c) : base(a, b, c)
    {
    }

    public override void doStuff()
    {
        //does stuff
    }
}


public class BarY : Foo
{
    public BarY(int a, int b, int c) : base(a, b, c)
    {
    }

    public override void doStuff()
    {
        //does stuff
    }
}

Upvotes: 1

Related Questions