Question

I want to create an inherited class for some 3rd party code and I'm having trouble implementing it in the way I want to.

The code below is a rough guide for what I want to do.

// 3rd party class
public class BaseClass
{
    public BaseClass(string Value1, string Value2)
    {
        // constructor does stuff with values
    }
    public string Method1()
    {
        // return value1
    }
    public string Method2()
    {
        // return value2
    }
}

// my class
public class SubClass : BaseClass
{
    public SubClass(string Key)
    {
        // decrypt key to get Value1 and Value2
        // create BaseClass(Value1, Value2)
    }
    public MyNewFunction(string Value)
    {
        // this is a function I've added, extending the base class
    }
}

There's a lot more going on than that example shows, but that is a basic example of the specific problem I'm facing. The 3rd party code requires a LOT of setting up and I just want to wrap all that up in a simple constructor, but still be able to call the base classes public methods without having to write a wrapper for each of them.

Is there a sensible way to do this or am I totally barking up the wrong tree?

Was it helpful?

Solution

I would not do it like that, I would use a factory instead. The idea of the factory is to put the creation of objects a bit further from the user code, is if you ever need to change how a certain object is created you only have to have a look at the factory.

Also have a look at the factory pattern . In general when creating objects try using a creational pattern, some can be found at this link given the GoF creational patterns. (Design Patterns by GoF (group of four) is one of the best reads with regards to object oriented patterns)

Like this:

public class BCFactory {
  public SubClass CreateInstance(string key)
  {
     var val1 = GetVal1FromKey(key);
     var val2 = GetVal2FromKey(key);
     // create the actual instance of the subclass
     var instance = new SubClass(val1, val2);

     return instance;
  }
}

public class SubClass {
   public SubClass(string val1, string val2) : base(val1, val2)
   {
      // Do nothing, we just instantiate the base class.
   }
}

Used like this:

var key = // your data
var factory = new BCFactory();
var instance = factory.CreateInstance(key);

OTHER TIPS

You can use a static method call in your base-constructor call to manipulate the data. This example will show how:

void Main()
{
    new SubClass("somekey");
}

public class BaseClass
{
    public BaseClass(string Value1, string Value2)
    {
        Console.WriteLine (Value1 + "\t" + Value2);
    }
}
public class SubClass : BaseClass
{
    public SubClass(string Key) : base(Key, Decrypt(Key))
    {

    }

    static string Decrypt(string val){
        return val + "_decrypted";
    }
}

Which prints

somekey somekey_decrypted

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top