views:

341

answers:

6

I would like to make use of few methods from couple of my old tested classes into my new class that I am building. Unfortunately, C# does not support multiple inheritance. How do I reuse code from these old classes? Do I just create them as member objects? or Do I have any other options?

+11  A: 

Generally, using composition instead of inheritance is the way forward, yes. If you could give a concrete example of the kind of thing you mean, that would make it easier to help find the appropriate approach though: it's not always the same.

Jon Skeet
A: 

if you have developed them as a component , use them dont inherite from them

Adinochestva
+4  A: 

Using them as member objects should be a good idea. Then you can also expose only the methods of interest, and adapt them if necessary.

Samuel Carrijo
This is called the delegation pattern, though with delegates in .NET that might sound a little confusing.
Thorarin
+4  A: 

You can recreate then as extension methods when they work on the same type.

public static void MyMethod( this MyType target ){}


MyType.MyMethod()

as noted below, if you have a class which derives from MyType or more common implements the interface the extension method works on, the extension works for those.

public class MyDerived : MyType{}

MyDerived.MyMethod()
pb
How would this help you to reuse code? You still have to define the extension method for your new class?
Thorarin
But they may be defined for generic types or for a more general interface, allowing the same extension method to be reused across a large number of classes.
jalf
A: 

You can fake it pretty easily like this:

public interface IFoo {
 void DoFoo();
}

public class Foo : IFoo {
 public void DoFoo() { Console.Write("Foo"); }
}

public class Bar {
 public void DoBar() { Console.Write("Bar"); }
}

public class FooBar : IFoo, Bar {
 private IFoo baseFoo = new Foo();
 public void DoFoo() { baseFoo.DoFoo(); }
}

//...

FooBar fooBar = new FooBar();

fooBar.DoFoo();
fooBar.DoBar();
IRBMe
+2  A: 
Eric Smith