Srdjan M.
Srdjan M.

Reputation: 3405

Pointer from derived class to base class C#

I have 100 classes that will inherit 1 base class. Derived class can have A and B property, just A or B property, or don't have them at all. I need a pointer, from derived class to base class, that will trigger every time I call A or B property from derived classes.

class D1 : Base
{
    int A { get; set; } // Point to Base A
}

class D2 : Base
{
    int A { get; set; } // Point to Base A
    int B { get; set; } // Point to Base B
}

class Base
{
    int A => ExampleA();
    int B => ExampleB();

    int ExampleA()
    {
        return 10;
    }

    int ExampleB()
    {
        return 15;
    }
}

static void Main(string[] args)
{
    D1 d1 = new D1();
    D2 d2 = new D2();

    d1.A; //return 10
    d2.A; //return 10
    d2.B; //return 15
}

Upvotes: 0

Views: 396

Answers (3)

CherryQuery
CherryQuery

Reputation: 458

If You want to inherit not everything but sometimes A, sometimes B and only sometimes A and B then it looks like You should not inherit from the base class at all. Looks more like You should create 2 interfaces and for example:

class D1 : IBaseA

class D2 : IBaseA, IBaseB

Upvotes: 4

MindSwipe
MindSwipe

Reputation: 7950

You'll want to make the properties on the base class virtual, so then classes that inherit from it can optionally override the behaivour. (Or you could also make the methods ExampleA and ExampleB virtual and optionally override that behaivour instead), like so:

public class Base
{
    // Made these properties get and set, instead of get (read) only
    // default values are for illustration purposes
    public virtual int A { get; set; } = 1;
    public virtual int B { get; set; } = 1;
}

public class Foo : Base
{
    public override int A { get; set; } = 10;
}

public class Bar : Base
{
    public override int B { get; set; } = 10;
}

Let's test it:

var a = new Foo();
var b = new Bar();

Console.WriteLine($"a.A: {a.A}, a.B: {a.B}");
Console.WriteLine($"b.A: {b.A}, b.B: {b.B}");

If you don't specify anything, Foo and Bar will implicitly have A and B with the same visibility as A and B in the Base class. You can't change the visiblity of a member of a class "after the fact" (i.e without changing it in the base class), so if only some of your classes should expose A or B you'll want to follow what CherryQuery said in their answer

Upvotes: 2

Piotr Wojsa
Piotr Wojsa

Reputation: 948

Actually in Base class you don't need A and B. Subclasses should then look like (assuming ExampleX methods are at least protected):

class D1 : Base
{
    public int A => ExampleA(); // note this is get-only property
}

Upvotes: 1

Related Questions