I want to subclass a large number of classes so that they will all contain a certain set of the same properties. What would be the right way to do it in order to avoid repetition? I thought of using generics like:
public class SuperT<T> : T
{
//the same set of properties
}
But the compiler says
Cannot derive from 'T' because it is a type parameter
EDIT: I am trying to subclass some classes in a third party assembly so I cannot use a base class.
For example, the types are "Image", "Label", "Button" etc and I want to subclass them all to contain a property like "Radius". (So that I would use SuperImage element in XAML and when I set it's Radius property from XAML, I will be able to run some certain logic.)
One other way I just thought of right now is using T4 templates. I wonder if there is a way to do this with generics without resorting to templates? I cannot understand why the compiler rejects it.
If these classes all share a common base class or common interface you could write an extension method.
public static class ShapeExetnsionsExtLib
{
public static double Radius(this ShapeBase shape){
return /*calculate radious*/;
}
}
From comments
I am trying to subclass some classes in a third party assembly so I cannot use a base class.
For example, the the types are "Image", "Label", "Button" etc and I want to subclass them all to contain a property like "radius".
Yes they share common base classes but I cannot add anything new to them.
I don't think generics have anything to do with this, however inheritance is probably what you're looking for.
There are two types of inheritance that you can use to subclass, and extension methods work to "superclass"... sort of.
Is-A inheritance
Has-A inheritance
And to simply add a similar method to a bunch of third party objects, you'll use an extension method.
Is-A inheritance
Use a base class if you've got similar method implementations.
public abstract class BaseFoo {
public void Bar() {
// actual code
}
}
public class Foo : BaseFoo
{
}
var foo = new Foo();
foo.Bar();
Use an Interface if you need to implement the same method on each class.
public interface IFoo {
void Bar();
}
public class Foo : IFoo {
public override void Bar(){
// bar implementation
}
}
var foo = new Foo();
foo.Bar();
Combining the two is also allowed, but you can only inherit on base class, where you can inherit multiple interfaces.
Has-A inheritance
This is particularly useful with dependency injection, but it's simply the notion that you have an instance of another class to work with. It's essentially a wrapper class for you to work with.
public class Foo {
private readonly ThirdPartyFoo _tpFoo;
void Foo(ThirdPartyFoo tpFoo) {
_tpFoo = tpFoo;
}
public void Bar(){
// now I can do something with _tpFoo;
_tpFoo.Bar();
}
}
var tpFoo = new ThirdPartyFoo();
var foo = new Foo(tpFoo);
foo.Bar(); // invokes the underlying tpFoo
Lastly, if you just need to add a method to existing classes, then you create an extension method.
public static class ViewExtensions()
{
// this assumes your Image, Button, Label all inherit from View.
public static Whatever Radius(this View view) {
// do your radius work.
}
}
Just Use a base class:
public class Base
{
public int Id { get; set; }
public string Name { get; set; }
}
And inherite from it:
public class A : Base
{
}
public class B : Base
{
}
In general, you want to use one of the answers already posted about using a base class and inheriting from that. However, if the classes are in a third party library and are marked as sealed, then you will need to create a wrapper class to use as a base class.
(Note that this option is a workaround and doesn't truly inherit from the third party class, so things in that class that are marked as protected won't be accessible without a liberal use of reflection.)
// The sealed class within another library
public sealed ThirdPartyClass
{
public ThirdPartyClass(int i) { }
public int SomeProperty { get; set; }
public int SomeMethod(string val) { return 0; }
public static void SomeStaticMethod() { }
}
// The wrapper class to use as a pseudo base class for ThirdPartyClass
public class BaseClass
{
private ThirdPartyClass _obj;
public BaseClass(int i) { _obj = new ThirdPartyClass(i); }
public int SomeProperty
{
get { return _obj.SomeProperty; }
set { _obj.SomeProperty = value; }
}
public int SomeMethod(string val) { return _obj.SomeMethod(val); }
public static SomeStaticMethod() { ThirdPartyClass.SomeStaticMethod(); }
}
// The child class that inherits from the "base" BaseClass
public class ChildClass : BaseClass
{
}
First of all, this might be a logical problem. What if you are going to extend a sealed class? Or Int32 class? Delegate?
Anyway, the way I recommend is to create an interface and implement all the functions you need in the subclass.
Related
Since multiple inheritance is bad (it makes the source more complicated) C# does not provide such a pattern directly. But sometimes it would be helpful to have this ability.
For instance I'm able to implement the missing multiple inheritance pattern using interfaces and three classes like that:
public interface IFirst { void FirstMethod(); }
public interface ISecond { void SecondMethod(); }
public class First:IFirst
{
public void FirstMethod() { Console.WriteLine("First"); }
}
public class Second:ISecond
{
public void SecondMethod() { Console.WriteLine("Second"); }
}
public class FirstAndSecond: IFirst, ISecond
{
First first = new First();
Second second = new Second();
public void FirstMethod() { first.FirstMethod(); }
public void SecondMethod() { second.SecondMethod(); }
}
Every time I add a method to one of the interfaces I need to change the class FirstAndSecond as well.
Is there a way to inject multiple existing classes into one new class like it is possible in C++?
Maybe there is a solution using some kind of code generation?
Or it may look like this (imaginary c# syntax):
public class FirstAndSecond: IFirst from First, ISecond from Second
{ }
So that there won't be a need to update the class FirstAndSecond when I modify one of the interfaces.
EDIT
Maybe it would be better to consider a practical example:
You have an existing class (e.g. a text based TCP client based on ITextTcpClient) which you do already use at different locations inside your project. Now you feel the need to create a component of your class to be easy accessible for windows forms developers.
As far as I know you currently have two ways to do this:
Write a new class that is inherited from components and implements the interface of the TextTcpClient class using an instance of the class itself as shown with FirstAndSecond.
Write a new class that inherits from TextTcpClient and somehow implements IComponent (haven't actually tried this yet).
In both cases you need to do work per method and not per class. Since you know that we will need all the methods of TextTcpClient and Component it would be the easiest solution to just combine those two into one class.
To avoid conflicts this may be done by code generation where the result could be altered afterwards but typing this by hand is a pure pain in the ass.
Consider just using composition instead of trying to simulate Multiple Inheritance. You can use Interfaces to define what classes make up the composition, eg: ISteerable implies a property of type SteeringWheel, IBrakable implies a property of type BrakePedal, etc.
Once you've done that, you could use the Extension Methods feature added to C# 3.0 to further simplify calling methods on those implied properties, eg:
public interface ISteerable { SteeringWheel wheel { get; set; } }
public interface IBrakable { BrakePedal brake { get; set; } }
public class Vehicle : ISteerable, IBrakable
{
public SteeringWheel wheel { get; set; }
public BrakePedal brake { get; set; }
public Vehicle() { wheel = new SteeringWheel(); brake = new BrakePedal(); }
}
public static class SteeringExtensions
{
public static void SteerLeft(this ISteerable vehicle)
{
vehicle.wheel.SteerLeft();
}
}
public static class BrakeExtensions
{
public static void Stop(this IBrakable vehicle)
{
vehicle.brake.ApplyUntilStop();
}
}
public class Main
{
Vehicle myCar = new Vehicle();
public void main()
{
myCar.SteerLeft();
myCar.Stop();
}
}
Since multiple inheritance is bad (it makes the source more complicated) C# does not provide such a pattern directly. But sometimes it would be helpful to have this ability.
C# and the .net CLR have not implemented MI because they have not concluded how it would inter-operate between C#, VB.net and the other languages yet, not because "it would make source more complex"
MI is a useful concept, the un-answered questions are ones like:- "What do you do when you have multiple common base classes in the different superclasses?
Perl is the only language I've ever worked with where MI works and works well. .Net may well introduce it one day but not yet, the CLR does already support MI but as I've said, there are no language constructs for it beyond that yet.
Until then you are stuck with Proxy objects and multiple Interfaces instead :(
I created a C# post-compiler that enables this kind of thing:
using NRoles;
public interface IFirst { void FirstMethod(); }
public interface ISecond { void SecondMethod(); }
public class RFirst : IFirst, Role {
public void FirstMethod() { Console.WriteLine("First"); }
}
public class RSecond : ISecond, Role {
public void SecondMethod() { Console.WriteLine("Second"); }
}
public class FirstAndSecond : Does<RFirst>, Does<RSecond> { }
You can run the post-compiler as a Visual Studio post-build-event:
C:\some_path\nroles-v0.1.0-bin\nutate.exe "$(TargetPath)"
In the same assembly you use it like this:
var fas = new FirstAndSecond();
fas.As<RFirst>().FirstMethod();
fas.As<RSecond>().SecondMethod();
In another assembly you use it like this:
var fas = new FirstAndSecond();
fas.FirstMethod();
fas.SecondMethod();
You could have one abstract base class that implements both IFirst and ISecond, and then inherit from just that base.
With C# 8 now you practically have multiple inheritance via default implementation of interface members:
interface ILogger
{
void Log(LogLevel level, string message);
void Log(Exception ex) => Log(LogLevel.Error, ex.ToString()); // New overload
}
class ConsoleLogger : ILogger
{
public void Log(LogLevel level, string message) { ... }
// Log(Exception) gets default implementation
}
This is along the lines of Lawrence Wenham's answer, but depending on your use case, it may or may not be an improvement -- you don't need the setters.
public interface IPerson {
int GetAge();
string GetName();
}
public interface IGetPerson {
IPerson GetPerson();
}
public static class IGetPersonAdditions {
public static int GetAgeViaPerson(this IGetPerson getPerson) { // I prefer to have the "ViaPerson" in the name in case the object has another Age property.
IPerson person = getPerson.GetPersion();
return person.GetAge();
}
public static string GetNameViaPerson(this IGetPerson getPerson) {
return getPerson.GetPerson().GetName();
}
}
public class Person: IPerson, IGetPerson {
private int Age {get;set;}
private string Name {get;set;}
public IPerson GetPerson() {
return this;
}
public int GetAge() { return Age; }
public string GetName() { return Name; }
}
Now any object that knows how to get a person can implement IGetPerson, and it will automatically have the GetAgeViaPerson() and GetNameViaPerson() methods. From this point, basically all Person code goes into IGetPerson, not into IPerson, other than new ivars, which have to go into both. And in using such code, you don't have to be concerned about whether or not your IGetPerson object is itself actually an IPerson.
In my own implementation I found that using classes/interfaces for MI, although "good form", tended to be a massive over complication since you need to set up all that multiple inheritance for only a few necessary function calls, and in my case, needed to be done literally dozens of times redundantly.
Instead it was easier to simply make static "functions that call functions that call functions" in different modular varieties as a sort of OOP replacement. The solution I was working on was the "spell system" for a RPG where effects need to heavily mix-and-match function calling to give an extreme variety of spells without re-writing code, much like the example seems to indicate.
Most of the functions can now be static because I don't necessarily need an instance for spell logic, whereas class inheritance can't even use virtual or abstract keywords while static. Interfaces can't use them at all.
Coding seems way faster and cleaner this way IMO. If you're just doing functions, and don't need inherited properties, use functions.
If you can live with the restriction that the methods of IFirst and ISecond must only interact with the contract of IFirst and ISecond (like in your example)... you can do what you ask with extension methods. In practice, this is rarely the case.
public interface IFirst {}
public interface ISecond {}
public class FirstAndSecond : IFirst, ISecond
{
}
public static MultipleInheritenceExtensions
{
public static void First(this IFirst theFirst)
{
Console.WriteLine("First");
}
public static void Second(this ISecond theSecond)
{
Console.WriteLine("Second");
}
}
///
public void Test()
{
FirstAndSecond fas = new FirstAndSecond();
fas.First();
fas.Second();
}
So the basic idea is that you define the required implementation in the interfaces... this required stuff should support the flexible implementation in the extension methods. Anytime you need to "add methods to the interface" instead you add an extension method.
Yes using Interface is a hassle because anytime we add a method in the class we have to add the signature in the interface. Also, what if we already have a class with a bunch of methods but no Interface for it? we have to manually create Interface for all the classes that we want to inherit from. And the worst thing is, we have to implement all methods in the Interfaces in the child class if the child class is to inherit from the multiple interface.
By following Facade design pattern we can simulate inheriting from multiple classes using accessors. Declare the classes as properties with {get;set;} inside the class that need to inherit and all public properties and methods are from that class, and in the constructor of the child class instantiate the parent classes.
For example:
namespace OOP
{
class Program
{
static void Main(string[] args)
{
Child somechild = new Child();
somechild.DoHomeWork();
somechild.CheckingAround();
Console.ReadLine();
}
}
public class Father
{
public Father() { }
public void Work()
{
Console.WriteLine("working...");
}
public void Moonlight()
{
Console.WriteLine("moonlighting...");
}
}
public class Mother
{
public Mother() { }
public void Cook()
{
Console.WriteLine("cooking...");
}
public void Clean()
{
Console.WriteLine("cleaning...");
}
}
public class Child
{
public Father MyFather { get; set; }
public Mother MyMother { get; set; }
public Child()
{
MyFather = new Father();
MyMother = new Mother();
}
public void GoToSchool()
{
Console.WriteLine("go to school...");
}
public void DoHomeWork()
{
Console.WriteLine("doing homework...");
}
public void CheckingAround()
{
MyFather.Work();
MyMother.Cook();
}
}
}
with this structure class Child will have access to all methods and properties of Class Father and Mother, simulating multiple inheritance, inheriting an instance of the parent classes. Not quite the same but it is practical.
Multiple inheritance is one of those things that generally causes more problems than it solves. In C++ it fits the pattern of giving you enough rope to hang yourself, but Java and C# have chosen to go the safer route of not giving you the option. The biggest problem is what to do if you inherit multiple classes that have a method with the same signature that the inheritee doesn't implement. Which class's method should it choose? Or should that not compile? There is generally another way to implement most things that doesn't rely on multiple inheritance.
If X inherits from Y, that has two somewhat orthogonal effects:
Y will provide default functionality for X, so the code for X only has to include stuff which is different from Y.
Almost anyplace a Y would be expected, an X may be used instead.
Although inheritance provides for both features, it is not hard to imagine circumstances where either could be of use without the other. No .net language I know of has a direct way of implementing the first without the second, though one could obtain such functionality by defining a base class which is never used directly, and having one or more classes that inherit directly from it without adding anything new (such classes could share all their code, but would not be substitutable for each other). Any CLR-compliant language, however, will allow the use of interfaces which provide the second feature of interfaces (substitutability) without the first (member reuse).
i know i know
even though its not allowed and so on, sometime u actualy need it so for the those:
class a {}
class b : a {}
class c : b {}
like in my case i wanted to do this
class b : Form (yep the windows.forms)
class c : b {}
cause half of the function were identical and with interface u must rewrite them all
Since the question of multiple inheritance (MI) pops up from time to time, I'd like to add an approach which addresses some problems with the composition pattern.
I build upon the IFirst, ISecond,First, Second, FirstAndSecond approach, as it was presented in the question. I reduce sample code to IFirst, since the pattern stays the same regardless of the number of interfaces / MI base classes.
Lets assume, that with MI First and Second would both derive from the same base class BaseClass, using only public interface elements from BaseClass
This can be expressed, by adding a container reference to BaseClass in the First and Second implementation:
class First : IFirst {
private BaseClass ContainerInstance;
First(BaseClass container) { ContainerInstance = container; }
public void FirstMethod() { Console.WriteLine("First"); ContainerInstance.DoStuff(); }
}
...
Things become more complicated, when protected interface elements from BaseClass are referenced or when First and Second would be abstract classes in MI, requiring their subclasses to implement some abstract parts.
class BaseClass {
protected void DoStuff();
}
abstract class First : IFirst {
public void FirstMethod() { DoStuff(); DoSubClassStuff(); }
protected abstract void DoStuff(); // base class reference in MI
protected abstract void DoSubClassStuff(); // sub class responsibility
}
C# allows nested classes to access protected/private elements of their containing classes, so this can be used to link the abstract bits from the First implementation.
class FirstAndSecond : BaseClass, IFirst, ISecond {
// link interface
private class PartFirst : First {
private FirstAndSecond ContainerInstance;
public PartFirst(FirstAndSecond container) {
ContainerInstance = container;
}
// forwarded references to emulate access as it would be with MI
protected override void DoStuff() { ContainerInstance.DoStuff(); }
protected override void DoSubClassStuff() { ContainerInstance.DoSubClassStuff(); }
}
private IFirst partFirstInstance; // composition object
public FirstMethod() { partFirstInstance.FirstMethod(); } // forwarded implementation
public FirstAndSecond() {
partFirstInstance = new PartFirst(this); // composition in constructor
}
// same stuff for Second
//...
// implementation of DoSubClassStuff
private void DoSubClassStuff() { Console.WriteLine("Private method accessed"); }
}
There is quite some boilerplate involved, but if the actual implementation of FirstMethod and SecondMethod are sufficiently complex and the amount of accessed private/protected methods is moderate, then this pattern may help to overcome lacking multiple inheritance.
I have an abstract class but and 6 different implementations of it. Now for one of them I would like to add an extra public method but would not like to add it to the abstract class because the other 5 implementations don't need it.
Is there a way of implementing this? I am getting an error when I add this new method without it being in the abstract class.
Here is the code:
namespace Results.Parser
{
public abstract class Parser<T> where T: ReportItem
{
public abstract string GetNodeName();
public abstract IEnumerable<ReportItem> ParseXml(TextReader stream);
public abstract List<ReportItem> SumValueOfDuplicateRows(List<T> reportList);
public virtual bool MeetsCriteria(ReportItem reportItem)
{
return reportItem.Value.SafeConvertToDecimal() != 0;
}
}
}
public class ElementParser : Parser<ReportItem>
{
public override string GetNodeName()
{
return "Element";
}
public override List<ReportItem> SumRiskValueOfDuplicateRows(List<ReportItem> reportList)
{
// do something
}
public void SerializeXml(TextReader stream)
{
//new method which is not in abstract class
}
public override IEnumerable<ReportItem> ParseXml(TextReader stream)
{
//do something
}
}
namespace Results.Producer
{
public class RepositoryManager
{
private void GetResponse(TextReader stream)
{
var parser = new ElementParser();
parser.SerializeXml(stream);
}
}
I am getting an error when I add this new method without it being in the abstract class.
A superclass reference to a subclass instance can't access methods not defined in the super class. You will need to explicitly cast your reference to a subclass reference type to be able to access the extra method from the subclass.
Let A be the abstract class and let B be the class where you have an extra method called extra. Let a be a reference of type A to an instance of type B. To access the extra method in B, do this :
((B)a).extra();
That being said, if only one of the classes needs additional behavior that is different, you should consider using composition over inheritance. See this answer that explains the famous duck problem that is similar to the situtation you are in currently
I have a user control that will handle images on a form. But depending on what the source is (web cam or ID scan or other video source) the user control is different.
But they share some common features so I want to create a base class.
My other controls all have some interface items that I need. I would like to declare the interface at the base level though and just implement at the class level. But virtual and override seems to be the closest way to get what I want. Is there any to do it, force the new class to implement the interface assigned at the base class? Looking around it look like making the class abstract (which I don't fully understand) might be a start. If it was just methods that might be alright, but I am also using properties. In that area I have hit a dead end in my searches for answers. Here is what I have so far. Am I on the right track? I just have not worked with abstract classes at all and only limited exposure to interfaces. From the research I think I have the method correct just not sure about the property.
public interface RequiredAnswer
{
void LabelRequiredFieldEmpty();
bool AnswerRequired{ get;}
}
public abstract partial class ExtImage : UserControl, RequiredAnswer
{
public virtual bool AnswerRequired
{
get
{
throw new NotImplementedException ("Answer Required");
}
}
public abstract void LabelRequiredFieldEmpty ()
{
//checkBox_AgreementAcceptedText.ForeColor = Color.Red;
}
So I would have a class
public partial class ExtImageWebCam : ExtImage
{
public override bool AnswerRequired
{
get
{
return valueFromThisClassThatMeansAnAnswerIsRequired;
}
}
public override void LabelRequiredFieldEmpty ()
{
// do something
}
}
When you declare a method abstract, you are basically saying that a child class must supply the definition of the method. You can make properties abstract. This sounds like it is exactly what you need.
Here is the MSDN article for further reference.
From MSDN
Properties
Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.
It is an error to use the abstract modifier on a static property.
An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
Continuing later
In this example, the class DerivedClass is derived from an abstract class BaseClass. The abstract class contains an abstract method, AbstractMethod, and two abstract properties, X and Y.
abstract class BaseClass // Abstract class
{
protected int _x = 100;
protected int _y = 150;
public abstract void AbstractMethod(); // Abstract method
public abstract int X { get; }
public abstract int Y { get; }
}
Abstract base class with an Interface
An abstract class must provide implementation for all interface members.
An abstract class that implements an interface might map the interface methods onto abstract methods. For example:
interface I
{
void M();
}
abstract class C : I
{
public abstract void M();
}
First of all, interfaces should start with an I by convention, so your interface would be IRequiredAnswer.
Second, if you want to force the inherited classes to implement their own methods rather than inheriting them, just make them abstract in the base class:
public abstract class ExtImage : UserControl, IRequiredAnswer
{
public abstract bool AnswerRequired { get; }
public abstract void LabelRequiredFieldEmpty ();
}
Your child classes would then have to implement the method and property.
You're on the right track. Here's a simple example of what you could do. Making the Bar() method abstract forces the inheritors to implement it.
public interface IFoo{
void Bar();
}
public abstract class BaseFoo : IFoo
{
public abstract void Bar();
public void Implemented(){
Debug.WriteLine("this is a shared implementation");
}
}
public class KungFoo : BaseFoo{
public override void Bar()
{
}
}
You are on the right track for the creation of an interface and then defining an abstract class for your purpose.
Standard naming conventions for an interface has been broken however, interfaces are usually prefixed with an I to help identify them
public interface IRequiresAnswer
{
void LabelRequiredFieldEmpty();
bool AnswerRequired { get; }
}
I would also suggest changing the AnswerRequired property to a function as your concrete class says "do somthing to find result". Properties are usually meant to be quick, so performing any calculation within a property is masking that real work takes place when you call the property. With a function it is more apparent to callers that the result will not be achieved immediately.
I have a base class that has a subclass (could be a struct i suppose but not sure if it's appropriate) and a method.
class Base
{
protected class SubClass
{
public string word;
public int number;
}
protected void SomeMethod()
{
this.SubClass.word //this is where I'm struggling
}
}
Then i have a couple child classes that implement my baseClass, instantiate the Base.SubClass and add some values to the instantiated class.
class ChildClass1 : Base
{
public childSubClass = new SubClass();
public void DoSomethingRidiculous()
{
childSubClass.word = "WhoFarted";
}
}
class ChildClass2 : Base
{
public childSubClass = new SubClass();
public void DoSomethingRidiculous()
{
childSubClass.word = "ItStinks";
}
}
If possible, I would like to be able to get the value of SubClass.word from within the Base class. I think that my attempt at implementing my idea is probably wrong.
I'm not sure that you really need subclassing / class nesting. Just move out class SubClass declaration and declare protected field/property of SubClass type instead.
public class SubClass
{
public string word;
public int number;
}
public class Base
{
protected SubClass subClassInstance = new SubClass();
protected void SomeMethod()
{
this.subClassInstance.word //this is where I'm struggling
}
}
Then you can access subClassInstance inside both ChildClass1 and ChildClass2
The base class has no field or property of type SubClass, so you definitely cannot do what you propose directly.
One solution would be to add the field
public childSubClass = new SubClass();
to class Base itself. Is there a problem with this?
The other solution would be to use reflection to get the value of the field, assuming that the object you are reflecting on does have such a field. This is really far-fetched and while it might technically allow you to do what you propose, it has a very bad code smell.
I'm not sure why you're making a Sub Class instead of just making those two properties of the base class, but the reason you're having trouble with this line :
this.SubClass.word //this is where I'm struggling
is because you're not instantiating SubClass as a property of the base class.
A base class can not (or should not) access members of derived classes, and usually not even know about derived classes (some exceptions apply, such as in the case of the State Pattern). If the base should have access to a member, it should be declared in the base. If derived classes should also be able to use that member, then mark the member as protected.
class Base
{
protected Foo someFoo;
void Frob()
{
// can access methods/properties of someFoo instance
}
}
class Child
{
public Child()
{
someFoo = new Foo(); // child can also access someFoo
}
}
Since multiple inheritance is bad (it makes the source more complicated) C# does not provide such a pattern directly. But sometimes it would be helpful to have this ability.
For instance I'm able to implement the missing multiple inheritance pattern using interfaces and three classes like that:
public interface IFirst { void FirstMethod(); }
public interface ISecond { void SecondMethod(); }
public class First:IFirst
{
public void FirstMethod() { Console.WriteLine("First"); }
}
public class Second:ISecond
{
public void SecondMethod() { Console.WriteLine("Second"); }
}
public class FirstAndSecond: IFirst, ISecond
{
First first = new First();
Second second = new Second();
public void FirstMethod() { first.FirstMethod(); }
public void SecondMethod() { second.SecondMethod(); }
}
Every time I add a method to one of the interfaces I need to change the class FirstAndSecond as well.
Is there a way to inject multiple existing classes into one new class like it is possible in C++?
Maybe there is a solution using some kind of code generation?
Or it may look like this (imaginary c# syntax):
public class FirstAndSecond: IFirst from First, ISecond from Second
{ }
So that there won't be a need to update the class FirstAndSecond when I modify one of the interfaces.
EDIT
Maybe it would be better to consider a practical example:
You have an existing class (e.g. a text based TCP client based on ITextTcpClient) which you do already use at different locations inside your project. Now you feel the need to create a component of your class to be easy accessible for windows forms developers.
As far as I know you currently have two ways to do this:
Write a new class that is inherited from components and implements the interface of the TextTcpClient class using an instance of the class itself as shown with FirstAndSecond.
Write a new class that inherits from TextTcpClient and somehow implements IComponent (haven't actually tried this yet).
In both cases you need to do work per method and not per class. Since you know that we will need all the methods of TextTcpClient and Component it would be the easiest solution to just combine those two into one class.
To avoid conflicts this may be done by code generation where the result could be altered afterwards but typing this by hand is a pure pain in the ass.
Consider just using composition instead of trying to simulate Multiple Inheritance. You can use Interfaces to define what classes make up the composition, eg: ISteerable implies a property of type SteeringWheel, IBrakable implies a property of type BrakePedal, etc.
Once you've done that, you could use the Extension Methods feature added to C# 3.0 to further simplify calling methods on those implied properties, eg:
public interface ISteerable { SteeringWheel wheel { get; set; } }
public interface IBrakable { BrakePedal brake { get; set; } }
public class Vehicle : ISteerable, IBrakable
{
public SteeringWheel wheel { get; set; }
public BrakePedal brake { get; set; }
public Vehicle() { wheel = new SteeringWheel(); brake = new BrakePedal(); }
}
public static class SteeringExtensions
{
public static void SteerLeft(this ISteerable vehicle)
{
vehicle.wheel.SteerLeft();
}
}
public static class BrakeExtensions
{
public static void Stop(this IBrakable vehicle)
{
vehicle.brake.ApplyUntilStop();
}
}
public class Main
{
Vehicle myCar = new Vehicle();
public void main()
{
myCar.SteerLeft();
myCar.Stop();
}
}
Since multiple inheritance is bad (it makes the source more complicated) C# does not provide such a pattern directly. But sometimes it would be helpful to have this ability.
C# and the .net CLR have not implemented MI because they have not concluded how it would inter-operate between C#, VB.net and the other languages yet, not because "it would make source more complex"
MI is a useful concept, the un-answered questions are ones like:- "What do you do when you have multiple common base classes in the different superclasses?
Perl is the only language I've ever worked with where MI works and works well. .Net may well introduce it one day but not yet, the CLR does already support MI but as I've said, there are no language constructs for it beyond that yet.
Until then you are stuck with Proxy objects and multiple Interfaces instead :(
I created a C# post-compiler that enables this kind of thing:
using NRoles;
public interface IFirst { void FirstMethod(); }
public interface ISecond { void SecondMethod(); }
public class RFirst : IFirst, Role {
public void FirstMethod() { Console.WriteLine("First"); }
}
public class RSecond : ISecond, Role {
public void SecondMethod() { Console.WriteLine("Second"); }
}
public class FirstAndSecond : Does<RFirst>, Does<RSecond> { }
You can run the post-compiler as a Visual Studio post-build-event:
C:\some_path\nroles-v0.1.0-bin\nutate.exe "$(TargetPath)"
In the same assembly you use it like this:
var fas = new FirstAndSecond();
fas.As<RFirst>().FirstMethod();
fas.As<RSecond>().SecondMethod();
In another assembly you use it like this:
var fas = new FirstAndSecond();
fas.FirstMethod();
fas.SecondMethod();
You could have one abstract base class that implements both IFirst and ISecond, and then inherit from just that base.
With C# 8 now you practically have multiple inheritance via default implementation of interface members:
interface ILogger
{
void Log(LogLevel level, string message);
void Log(Exception ex) => Log(LogLevel.Error, ex.ToString()); // New overload
}
class ConsoleLogger : ILogger
{
public void Log(LogLevel level, string message) { ... }
// Log(Exception) gets default implementation
}
This is along the lines of Lawrence Wenham's answer, but depending on your use case, it may or may not be an improvement -- you don't need the setters.
public interface IPerson {
int GetAge();
string GetName();
}
public interface IGetPerson {
IPerson GetPerson();
}
public static class IGetPersonAdditions {
public static int GetAgeViaPerson(this IGetPerson getPerson) { // I prefer to have the "ViaPerson" in the name in case the object has another Age property.
IPerson person = getPerson.GetPersion();
return person.GetAge();
}
public static string GetNameViaPerson(this IGetPerson getPerson) {
return getPerson.GetPerson().GetName();
}
}
public class Person: IPerson, IGetPerson {
private int Age {get;set;}
private string Name {get;set;}
public IPerson GetPerson() {
return this;
}
public int GetAge() { return Age; }
public string GetName() { return Name; }
}
Now any object that knows how to get a person can implement IGetPerson, and it will automatically have the GetAgeViaPerson() and GetNameViaPerson() methods. From this point, basically all Person code goes into IGetPerson, not into IPerson, other than new ivars, which have to go into both. And in using such code, you don't have to be concerned about whether or not your IGetPerson object is itself actually an IPerson.
In my own implementation I found that using classes/interfaces for MI, although "good form", tended to be a massive over complication since you need to set up all that multiple inheritance for only a few necessary function calls, and in my case, needed to be done literally dozens of times redundantly.
Instead it was easier to simply make static "functions that call functions that call functions" in different modular varieties as a sort of OOP replacement. The solution I was working on was the "spell system" for a RPG where effects need to heavily mix-and-match function calling to give an extreme variety of spells without re-writing code, much like the example seems to indicate.
Most of the functions can now be static because I don't necessarily need an instance for spell logic, whereas class inheritance can't even use virtual or abstract keywords while static. Interfaces can't use them at all.
Coding seems way faster and cleaner this way IMO. If you're just doing functions, and don't need inherited properties, use functions.
If you can live with the restriction that the methods of IFirst and ISecond must only interact with the contract of IFirst and ISecond (like in your example)... you can do what you ask with extension methods. In practice, this is rarely the case.
public interface IFirst {}
public interface ISecond {}
public class FirstAndSecond : IFirst, ISecond
{
}
public static MultipleInheritenceExtensions
{
public static void First(this IFirst theFirst)
{
Console.WriteLine("First");
}
public static void Second(this ISecond theSecond)
{
Console.WriteLine("Second");
}
}
///
public void Test()
{
FirstAndSecond fas = new FirstAndSecond();
fas.First();
fas.Second();
}
So the basic idea is that you define the required implementation in the interfaces... this required stuff should support the flexible implementation in the extension methods. Anytime you need to "add methods to the interface" instead you add an extension method.
Yes using Interface is a hassle because anytime we add a method in the class we have to add the signature in the interface. Also, what if we already have a class with a bunch of methods but no Interface for it? we have to manually create Interface for all the classes that we want to inherit from. And the worst thing is, we have to implement all methods in the Interfaces in the child class if the child class is to inherit from the multiple interface.
By following Facade design pattern we can simulate inheriting from multiple classes using accessors. Declare the classes as properties with {get;set;} inside the class that need to inherit and all public properties and methods are from that class, and in the constructor of the child class instantiate the parent classes.
For example:
namespace OOP
{
class Program
{
static void Main(string[] args)
{
Child somechild = new Child();
somechild.DoHomeWork();
somechild.CheckingAround();
Console.ReadLine();
}
}
public class Father
{
public Father() { }
public void Work()
{
Console.WriteLine("working...");
}
public void Moonlight()
{
Console.WriteLine("moonlighting...");
}
}
public class Mother
{
public Mother() { }
public void Cook()
{
Console.WriteLine("cooking...");
}
public void Clean()
{
Console.WriteLine("cleaning...");
}
}
public class Child
{
public Father MyFather { get; set; }
public Mother MyMother { get; set; }
public Child()
{
MyFather = new Father();
MyMother = new Mother();
}
public void GoToSchool()
{
Console.WriteLine("go to school...");
}
public void DoHomeWork()
{
Console.WriteLine("doing homework...");
}
public void CheckingAround()
{
MyFather.Work();
MyMother.Cook();
}
}
}
with this structure class Child will have access to all methods and properties of Class Father and Mother, simulating multiple inheritance, inheriting an instance of the parent classes. Not quite the same but it is practical.
Multiple inheritance is one of those things that generally causes more problems than it solves. In C++ it fits the pattern of giving you enough rope to hang yourself, but Java and C# have chosen to go the safer route of not giving you the option. The biggest problem is what to do if you inherit multiple classes that have a method with the same signature that the inheritee doesn't implement. Which class's method should it choose? Or should that not compile? There is generally another way to implement most things that doesn't rely on multiple inheritance.
If X inherits from Y, that has two somewhat orthogonal effects:
Y will provide default functionality for X, so the code for X only has to include stuff which is different from Y.
Almost anyplace a Y would be expected, an X may be used instead.
Although inheritance provides for both features, it is not hard to imagine circumstances where either could be of use without the other. No .net language I know of has a direct way of implementing the first without the second, though one could obtain such functionality by defining a base class which is never used directly, and having one or more classes that inherit directly from it without adding anything new (such classes could share all their code, but would not be substitutable for each other). Any CLR-compliant language, however, will allow the use of interfaces which provide the second feature of interfaces (substitutability) without the first (member reuse).
i know i know
even though its not allowed and so on, sometime u actualy need it so for the those:
class a {}
class b : a {}
class c : b {}
like in my case i wanted to do this
class b : Form (yep the windows.forms)
class c : b {}
cause half of the function were identical and with interface u must rewrite them all
Since the question of multiple inheritance (MI) pops up from time to time, I'd like to add an approach which addresses some problems with the composition pattern.
I build upon the IFirst, ISecond,First, Second, FirstAndSecond approach, as it was presented in the question. I reduce sample code to IFirst, since the pattern stays the same regardless of the number of interfaces / MI base classes.
Lets assume, that with MI First and Second would both derive from the same base class BaseClass, using only public interface elements from BaseClass
This can be expressed, by adding a container reference to BaseClass in the First and Second implementation:
class First : IFirst {
private BaseClass ContainerInstance;
First(BaseClass container) { ContainerInstance = container; }
public void FirstMethod() { Console.WriteLine("First"); ContainerInstance.DoStuff(); }
}
...
Things become more complicated, when protected interface elements from BaseClass are referenced or when First and Second would be abstract classes in MI, requiring their subclasses to implement some abstract parts.
class BaseClass {
protected void DoStuff();
}
abstract class First : IFirst {
public void FirstMethod() { DoStuff(); DoSubClassStuff(); }
protected abstract void DoStuff(); // base class reference in MI
protected abstract void DoSubClassStuff(); // sub class responsibility
}
C# allows nested classes to access protected/private elements of their containing classes, so this can be used to link the abstract bits from the First implementation.
class FirstAndSecond : BaseClass, IFirst, ISecond {
// link interface
private class PartFirst : First {
private FirstAndSecond ContainerInstance;
public PartFirst(FirstAndSecond container) {
ContainerInstance = container;
}
// forwarded references to emulate access as it would be with MI
protected override void DoStuff() { ContainerInstance.DoStuff(); }
protected override void DoSubClassStuff() { ContainerInstance.DoSubClassStuff(); }
}
private IFirst partFirstInstance; // composition object
public FirstMethod() { partFirstInstance.FirstMethod(); } // forwarded implementation
public FirstAndSecond() {
partFirstInstance = new PartFirst(this); // composition in constructor
}
// same stuff for Second
//...
// implementation of DoSubClassStuff
private void DoSubClassStuff() { Console.WriteLine("Private method accessed"); }
}
There is quite some boilerplate involved, but if the actual implementation of FirstMethod and SecondMethod are sufficiently complex and the amount of accessed private/protected methods is moderate, then this pattern may help to overcome lacking multiple inheritance.