-2

This is my problem: I have a Class A that is used (instantiated) several times within a Class B.

I need to change the behaviour of the Class A, mainly the constructor, and then I derived it with Class C. Class C: Class A

I would like that Class B using in its methods Class C instead of Class A, avoiding to override all the methods that used it. Is it this possible?

Many thanks


I was not clear, therefore let me try to explain better with code.

Public Class A
{
`// Simple constructor
    public A(params[])
    {
        // things here
    }
}

Public Class C : A
{
    // Constructor doing different thing then base
    public C(params[]): base(params[])
    {
        // do different things here
    }
}

Public class B
{
    public B(params[])
    {    }

    public method_A(params[])
    {
        A _temp = new A(params[]);
        // do things here with A
    }
}

I use B in my program, but I would like that for one istance of B it uses A and for another instance of B it uses C instead of A.

Something like:

Main()
{
   B _instance1 = new B();

   B _instance2 = new B(); 

   // use instance 1
   _instance1.method_A(...);
   // use instance 2 
   _instance2.method_A(...); // do something here for using C instead of A in the method
}
  • 2
    Provide the sample code. – Sham Sep 27 '18 at 06:07
  • Could you please elaborate a little bit more? Maybe a short example would be helpfull – royalTS Sep 27 '18 at 06:08
  • 1
    Replace `new A()` in class `B` with `new C()` _(when I correctly understand your question, this change should be done)_. – Julo Sep 27 '18 at 06:09
  • Sounds like you want to look into the factory pattern. Probably "just" a simple factory method will suffice here. So rather than calling `new A()` all over the place, you have *one* method like `public A CreateA() { return new A(); }` and call *that* whenever you need a new instance of `A`. If you did that, then changing it now would be very easy: `public A CreateA() { return new C(); }` (since `C : A` there shouldn't be a problem; other than naming maybe). You might have to bite the bullet and refactor to this now so it would be easier next time, when you need `D : A`. – Corak Sep 27 '18 at 07:27
  • Thank you for the answers. I added some note and code, that maybe can help a little bit. The matter is a little bit different from my poor initial question. – Aldo Spano Sep 28 '18 at 20:44

1 Answers1

1

Just instantiate class C in class B and use it as you would class A, it will have the same functions as A with your added logic in class C.

in your constructor it might be worthwhile to do something like:

public class C : A
{
    public C() : base()
    {
     // do stuff
    }
}

so that it will also call A's constructor.

Minijack
  • 726
  • 7
  • 23