ok I'm little lost with generics in C#
I have this generic interface
interface IInvoiceStorage<T>
where T : class
{
void Persist(T Invoice);
}
with two classes implementing the interface
public class FacturaStorageForSQLServer:IInvoiceStorage<EVT>
{
public void Persist(EVT Invoice)
{
/*Implementation*/
}
}
public class FacturaStorageForMySQLServer:IInvoiceStorage<EVTFruit>
{
public void Persist(EVTFruit Invoice)
{
/*Implementation*/
}
}
The problem comes when I want to declare this in my service class
public class invoice_service
{
IInvoiceStorage Storage;
public invoice_service(IInvoiceStorage storage)
{
Storage=_storage;
}
}
C# tells me that I have to declare de type of the interface but if I do that then my service class is going to depend from the implementation and not from the interface.
Suggestions??
UPDATE 1:
Sorry If I declare the type the interface is going to depend only from the implementations using that type but what happens if I have two implementations using two different types for example EVT and EVTFruit.
I was thinking to use another interface to establish a relationship between EVT and EVTFruit but they can be two totally different objects so I'm not sure if it is a good idea.
You could change your class a little bit:
public class invoice_service<T> where T : class
{
IInvoiceStorage<T> Storage;
public invoice_service(IInvoiceStorage<T> storage)
{
Storage=_storage;
}
}
Which would allow you to use the interface correctly and keep it generic.
Depending on your needs, you could also defined non-generic version of that interface:
public interface IInvoiceStorage
{
...
}
And make classes inherit from this interface, too.
public class FacturaStorageForSQLServer : IInvoiceStorage, IInvoiceStorage<EVT>
public class FacturaStorageForMySQLServer : IInvoiceStorage, IInvoiceStorage<EVTFruit>
That way you can use non-generic version of interface in invoice_service class.
But, as I said, depending on your needs if you can make functionality of that interface independent of type (for example, List<T> also implements IList for list functionalities, without type).
After trying your suggestions and reading some blogs here is what I did and is fulfilling my requeriments at least for now. The problem was resolved when I realized that I shouldn't use the generic repository pattern as a repository itself but as a helper of the repository! At the end what I'm doing is wrapping the generic interfaces inside of another layer of non-generic interfaces.
a Service class calling for an IInvoiceRepositoryService implementation
public class InvoiceService
{
private IInvoiceRepositoryService RepositoryService;
public SQLInvoiceService(IInvoiceRepositoryService _RS)
{
RepositoryService=_RS;
}
}
and their respective implementation for EVT and EVTFruit.
public class EVTRepository:IInvoiceRepositoryService
{
private IInvoiceStorage<EVT> EVTStorage;
public EVTInvoiceRepository(IInvoice<EVT> _EVT)
{
EVTStorage=_EVT;
}
}
public class EVTStorageForSQLServer: IInvoiceStorage<EVT>
{
/*Implementation*/
}
public class EVTStorageForMySQLServer: IInvoiceStorage<EVT>
{
/*Implementation*/
}
public class EVTFruitRepository:IInvoiceRepositoryService
{
private IInvoiceStorage<EVT> EVTFruitStorage;
public EVTFruitInvoiceRepository(IInvoice<EVTFruit> _EVTFruit)
{
EVTFruitStorage=_EVTFruit;
}
}
public class EVTFruitStorageForSQLServer: IInvoiceStorage<EVTFruit>
{
/*Implementation*/
}
public class EVTFruitStorageForMySQLServer: IInvoiceStorage<EVTFruit>
{
/*Implementation*/
}
At the end this was just a design problem I think. I'm going to mark Ron Beyer's response as the answer because is valid and it was really straightforward
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'm trying to define an interface that has a function that only accepts the class type which implements it. Here is what I have so far:
public interface ICombinableAction : IAction {
public bool CombineActions(ICombinableAction toCombine);
}
public class MoveAllObjects : ICombinableAction {
public bool CombineActions(ICombinableAction toCombine) {
if (!(toCombine is MoveAllObjects)) {
// This isn't possible, inform the caller
return false;
}
... // Combining logic
return true;
}
}
Unfortunately, as the function can't check at compiletime the type of the object passed in I have to handle the case where an incompatible class is used, and then handle that in the caller.
Ideally this would be possible by defining the interface such that only instances of the same class are possible, something along the lines of:
public interface ICombinableAction : IAction {
public void CombineActions(Implementor toCombine);
}
public class MoveAllObjects : ICombinableAction {
public void CombineActions(MoveAllObjects toCombine) {
... // Combining logic
}
}
I suspect that isn't possible due to the anwer in C# Interfaces: Is it possible to refer to the type that implements the interface within the interface itself?. I suspect that this question Why C# doesn't allow inheritance of return type when implementing an Interface is also skirting around the same issue that I am. Neither of these questions helped me to reach a solution for my particular problem though.
What would be a good solution in this case?
If i understood your problem correctly - you can achieve something like this with generics:
public interface ICombinableAction<T> where T : ICombinableAction<T>
{
public void CombineActions(T toCombine);
}
public class MoveAllObjects : ICombinableAction<MoveAllObjects>
{
public void CombineActions(MoveAllObjects toCombine)
{
}
}
I have two interfaces implemented by one main class. How can i refactor my code in a way that on implementing each contract, the methods of each contract has a different value for a parameter such as DatabaseName.
Example :
Class1 Implements Interface1,Interface2
Interface1.GetData() has DatabaseName set to Database 1
Interface2.GetData() has DatabaseName set to Database 2
I can configure those value in the methods GetData() but i want a cleaner way of doing it.
Any pattern recommendation be that DI ,Domain driven ,even basic inheritance example which accomplishes the above is what i am looking for.
It sounds like all you need is explicit interface implementation:
public class Class1 : Interface1, Interface2
{
// Note the lack of access modifier here. That's important!
Data Interface1.GetData()
{
// Implementation for Interface1
}
Data Interface2.GetData()
{
// Implementation for Interface2
}
}
Obviously the two methods can call a common method with a parameter to specify the database name or similar.
Refactoring is usually motivated by noticing a code smell and the very fact that you ended up in a situation where you have to implement 2 abstraction which expose similar functionality is the code smell.
Without having more understanding of the problem I might not be able to provide you a conclusive answer but with limited understanding this is what I would propose. Have 2 different concrete implementation each implementing one interface and have a factory which would be injected to client and make the client make the deliberate decision which one of these implementation is needed. In case these concrete classes share common functionality you can always abstract that into a common parent class.
public interface ISQLReader
{
string GetData();
}
public interface IOracleReader
{
string GetData();
}
public abstract class Reader
{
protected void CommonFunctionaility()
{
}
}
public class MSSQLReader : Reader, ISQLReader
{
public string GetData()
{
return "MSSQL";
}
}
public class OracleReader : Reader, IOracleReader
{
public string GetData()
{
return "Oracle";
}
}
public interface IReaderFactory
{
OracleReader CreateOracleReader();
MSSQLReader CreateMSSQLReader();
}
public class ReaderFactory : IReaderFactory
{
public MSSQLReader CreateMSSQLReader() => new MSSQLReader();
public OracleReader CreateOracleReader() => new OracleReader();
}
public class ReaderClient
{
private IReaderFactory _factory;
public ReaderClient(IReaderFactory factory)
{
this._factory = factory;
}
}
Explicit interface implementation is technique that should restrict usage of the functionality until the client has made and explicit cast there by making a deliberate decision.
I feel like I've been using these pattern families quite many times, however, for me it's hard to see the differences as their definitions are quite similar. Basicaly it seems like all of them is about wrapping another object or objects to extend or wrap their behavior with extra stuff.
For a quick example implementing a caching mechanism over a repository pattern seems to be this situation. Here is a quick sample C# code I would probably start with.
public interface IRepository {
IEnumerable<T> GetItems<T>();
}
public class EntityFrameworkRepository : IRepository {
...
}
public class CachedRepository : IRepository {
private IRepository _repository;
private ICacheProvider _cache;
public CachedRepository(IRepository repository, ICacheProvider cache) {
this._repository = repository;
this._cache = cache;
}
public IEnumerable<T> GetItems<T>() {
...
}
}
Which one of these patterns apply to this situation for example? Could anyone clarify briefly the differences in theory and in practice?
In theory they are the same, it's the intent that differentiates one pattern from the other:
Decorator:
Allows objects to be composed/add capabilities by wrapping them with a class with the same interface
Adapter:
Allows you to wrap an object without a known interface implementation
so it adheres to an interface. The point is to "translate" one interface into another.
Wrapper:
Never heard of this as a design pattern, but I suppose it's just a common name for the above
The example you specify I would categorize as a decorator: The CacheRepository decorates an IRepository to add caching capabilities.
A programmer may write a class A with a focus on holding an object of another class B. Class A would be referred to as a wrapper for class B. Why have class A wrap around class B? To decorate or adapt it. Decorators and adapters are wrappers.
Imagine that class A is written such that it implements the interface of class B by calling the methods of its class B object. It could then be used in place of class B. There's no point in this other than the fact that it gives the programmer the opportunity to add some code before or after the calls to the methods of the class B object. This version of class A would be called a decorator of class B. Decorators leave the interface the same while adding some behavior.
interface ICatInterface {
public void wakeUp();
}
class Cat implements ICatInterface {
public void wakeUp() {
System.out.println("I came. I saw. I napped.");
}
}
class YogaCat implements ICatInterface {
private ICatInterface cat;
public YogaCat(ICatInterface cat) {
this.cat = cat;
}
public void wakeUp() {
System.out.println("[Stretch]"); // <- This is the decoration.
cat.wakeUp();
}
}
See this example of a more complicated way to use this pattern for composing objects of differing behavior during runtime.
Imagine now that class A is written such that it implements some interface C, but is implemented mostly via calls to the methods of its class B object. This is a way to translate the methods available in class B to interface C. This version of class A would be called an adapter of class B. It's like when you want to charge your phone. There are adapters that go from wall or car power source to USB port. Adapters change the interface to some other interface, but don't necessarily add any behaviors.
interface TakeDirectionsInterface {
public void turnLeft();
public void turnRight();
public void go();
public void stop();
}
class Driver {
public enum TurnDirection
{
CLOCKWISE, COUNTERCLOCKWISE;
}
public enum FootPedal
{
ACCELERATOR, BRAKE, CLUTCH;
}
public void turnSteeringWheel(TurnDirection direction) {
System.out.println("Turning the steering wheel " + direction.toString() + ".");
}
public void pressPedal(FootPedal pedal) {
System.out.println("Pressing the " + pedal.toString() + "pedal.");
}
}
class DriverAdapter implements TakeDirectionsInterface {
private Driver driver;
public DriverAdapter(Driver driver) {
this.driver = driver;
}
public void turnLeft(){
driver.turnSteeringWheel(Driver.TurnDirection.COUNTERCLOCKWISE);
}
public void turnRight(){
driver.turnSteeringWheel(Driver.TurnDirection.CLOCKWISE);
}
public void go(){
driver.pressPedal(Driver.FootPedal.ACCELERATOR);
}
public void stop(){
driver.pressPedal(Driver.FootPedal.BRAKE);
}
}
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.