Workaround for Multiple Inheritance in C# - c#

I have to implement classes to transfer files to USB (class USBTransfer) and over FTP (class FTPTransfer). Since both the classes use some common methods (like getting the filename, reading some parameters etc.) so, I have implemented those methods in an another class (class FileOperations). I have inherited both the classes (i.e. class USBTransfer and class FTPTransfer) from the class FileOperations.
class FileOperations
{
protected void CommonMethod1();
protected void CommonMethod2();
}
class USBTransfer : FileOperations
{
}
class FTPTransfer : FileOperations
{
}
PROBLEM: During the file transfer operations, I set different states (not using the state machine design pattern though). I want to use a ABSTRACT class for this purpose with the following structure.
abstract class FileTransferStateMachine
{
//Public
public enum FileTransferStates { Idle = 0, FileCopyingState = 1, SuccessfullyCopiedState = 2 }
public static FileTransferStates CurrentState = FileTransferStates.Idle;
abstract protected void IdleState();
abstract protected void FileCopyingState();
abstract protected void SuccessfullyCopiedState();
}
But in C# it is not allowed to have multiple inheritance.
QUESTION: I know that I can use interface. But you cannot have variables and in that case both of my classes (i.e. class USBTransfer and class FTPTransfer) will have their own variables for the following
public enum FileTransferStates { Idle = 0, FileCopyingState = 1, SuccessfullyCopiedState = 2 }
public static FileTransferStates CurrentState = FileTransferStates.Idle;
I want to reduce redundancy and want to force to have same variables/methods (hmm...same methods can be achieved by interface) for the state machine.
Question PART-2: I can transfer files to USB or FTP as mentioned above but both the transfer operations have some common states like IdleState, FileCopyingState or SuccessfullyCopiedState which have their corresponding methods (i.e. IdleState(), FileCopyingState() or SuccessfullyCopiedState()). I want to FORCE both the classes to implement these methods (i.e. IdleState(), FileCopyingState() or SuccessfullyCopiedState()). If any class forgets to implement any method then, I should get a compiler error. Basically, the FileTransferStateMachine should be an interface/abstract class whose methods should be overridden in USBTransfer and FTPTransfer classes (which are already inheriting another class called FileOperations).

Use composition (and avoid static state members) :
abstract class FileOperations
{
protected void CommonMethod1();
protected void CommonMethod2();
protected FileTransferStateMachine Statemachine { get; set; }
}
Edit, regarding Part 2:
When you want to force the concrete classes to implement each of those methods then an interface IFileTransferStateMachine is exactly right.
You could also derive FileOperations from the StateMachine:
abstract class FileOperations: FileTransferStateMachine { }
but I would use an interface, it can be applied more granular.

Addressing both of the parts you say are a problem:
FileTransferStates can be moved out of the class, placed directly in the namespace (probably in its own file). Then it can be used by both implementations without being redefined
CurrentState can be made a non-static property (not field). Properties can be put on an interface, so they don't need an abstract class. Properties are highly recommended over fields for public members anyway, and as others have said, static isn't appropriate here.
As others have mentioned, another option is to use one of these two classes as a dependency instead of a base class. I.e. using composition instead of inheritance.

Related

Sharing implementation of interfaces in C#

I have some interfaces that need some simple implementation, but I have a handful of them, like for instance (not actual code, just example)
interface ISelectable
{
public bool IsSelected;
public void Select();
}
public class Selectable : ISelectable
{
public bool IsSelected {get;set}
public void Select()=> IsSelected = true;
}
Then I might have IStorable, which allows storing stuff in the database, like:
public interface IStorable
{
public void Store();
...
}
public class Storable : IStorable
{
private stuff...
public void Store() { storing code }
}
The question is:
I have
elements that are IStorable but not ISelectable,
elements that are ISelectable and no IStorable,
and elements that are both.
Actually... I have MORE of these classes. So the combinations grow fast.
As far as I know, the only way to share the code is to have a base class implement the interface, then your class inherits from this base class. Like:
public class GameCard : Selectable { ....
But this would mean that the only way to have a class that inherits the code for Selectable, and the code for Storable is to have a base class doing both, something like public class StorableAndSelectable: IStorable, ISelectable But this makes no sense, especially when you want to have different storing methods...
What's the proper way to have your classes share the implementation code of the interfaces it implements? Having the implementation for each of them in one file, and feeding this "file" to all classes that need it?
I would consider if inheritance is the correct approach for such simple properties. There are some possible alternatives. Using inheritance to include functionality is called implemention inheritance and is generally frowned upon. For simple stuff like this it provides little benefit, and for more complicated logic it ties the derived class to the base class to tightly.
To store an object I would probably suggest the repository pattern, that way you do not need a special interface.
To handle things like if a object is selected, the easiest option is probably just to have a settable property in the interface: bool IsSelected {get;set;}. This is trivially implementable by all derived classes, there is no real advantage of a implementation of just that interface, at least not outside of testing/dummy objects.
In some cases you can use a Func<T, bool> to describe how to determine if some arbitrary type is selected. In some cases it might be useful to use composition, i.e. use a separate class to describe selection, and have your game objects contain a property of this class.
Starting from C# 8.0 you can have default method implementation in interface definition
interface IA
{
void M() { WriteLine("IA.M"); }
}
class C : IA { } // OK
IA i = new C();
i.M(); // prints "IA.M"
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods
According to your classes you can do something like this
interface ISelectable
{
public bool IsSelected;
public void Select() => IsSelected = true;
}

I don't understand inheritance with base classes

My understanding of inheritance is pretty basic.
I want to create a base class, which implements IDisposable and then let other classes with functionality inherit from that base class, so that they share a base type.
It would allow me to put every object into one list, so that I can dispose of everything in one go, when I want to clean up.
The thing is, a class in C# can only inherit once and otherwise only use interfaces.
Now, how can classes like Thread, inherit from my base class without me having to basically code the Thread class all over again?
It may sound dumb, but in short: I want to let already existing classes inherit a base class of my choosing without loosing its functionality. (So that all classes used in a project have a common base, to be summed up into one object type, for like List)
Is that even possible?
If your aim is to simply store a list of objects which can be disposed, then you want a List<IDisposable>. Any class which, directly or indirectly implements that interface can be stored therein.
var disposables = new List<IDisposable>();
disposables.Add(new MyClass1());
disposables.Add(new SomeClass());
disposables.Add(new AnotherClass());
disposables.ForEach(d => d.Dispose());
Whether this is a worthwhle pattern, I'm not convinced!
Example you given invlolves interface IDisposable. In C#, class can implement multiple interfaces.
On the other hand, in C# class may inherit from exactly one class.
Having said that, it is not always good idea to inherit from classes, as it very limiting. Instead I would suggest composition: wiki
For example, I would suggest something like composition design pattern (it is a small variation, as the composite does not have collection of objects, rather just one object):
public interface IFoo
{
void DoFooStuff();
}
public class Foo : IFoo
{
public void DoFooStuff() {...};
}
public class ShouldImplementFoo : IFoo
{
// Composition, you need to initialize it some time
private Foo _foo;
public void DoFooStuff() { _foo.DoFooStuff(); }
}
EDIT
After rethinking your problem, you seem to want to put some set of objects (of different classes) in a list, so you can execute some defined action on each object in a list.
The simpliest is: define interface with your defined action:
public interface IMyIntf
{
void MyDesiredAction();
}
And now, make all classes implement it. Now you might think "Well, now I need to implement this method everywhere..." - nothing like that! Just use adapter design pattern, for example, having class:
public class MyConcreteClass
{
public void ActionIWishToExecuteOnThisObject()
{ ... }
}
you just modify it to:
public class MyConcreteClass : IMyIntf
{
public void ActionIWishToExecuteOnThisObject()
{ ... }
// implement interface
public void MyDesiredAction()
{
ActionIWishToExecuteOnThisObject();
}
}
Now, you can use some aggregate, like List<IMyIntf>, place all objects you are interested in there and do:
foreach(var item in myList)
item.MyDesiredAction();
A class can inherits from an ancestor class (else Object, the root of all).
Also it can implements some interfaces (or none).
A class can have non implemented members as being abstract, so the class is abstract.
Also members can be virtual to enable polymorphism (abstract members are).
Once implemented, a thing is available in the class that can be instantiated for real if not abstract, and is available for all children too, except whose that are private which are hidden in subclass.
There is no need to repeat and that is one of the power of OOP.
Doing so, using abstraction, encapsulation, inheritance and polymorphism, after stuying the real world and the domain where we work, we can design a projection of this real world, a view in our mind, with concepts having data (fields and properties) and operations (methods), classed in artifacts (objects) and things like relations, composition, aggregation, interfaces, components, controls, and so on.
Thus we can factorize processings to not repeat like for example:
Having a Animal class and Cat and Dog child classes,
We put in animal the Size and the Color aspect,
As well as the Eat and Walk methods implemented for all animals,
And an abstract non-implemented DoSound.
Therefore:
In concrete classes Cat and Dog we don't implement again the things,
Except DoSound that is particular for each real animal gender.
Concerning interfaces, they are virtual contracts.
For example we can have animals and buildings that have nothing in common, at first look (we will not go back to atoms and photons), but we want to be able to manage instances of objects like cat and dog, as well as house and museum to take a photo.
To acheive that we define an interface IPhotoTaking and when defining previous classes, we add that they implements this interface.
Code sample:
public interface IPhotoTaking
{
Image TakePhoto();
}
public abstract class Animal : IPhotoTaking
{
public int Size { get; set; }
public Color Color { get; set; }
public void Eat() { ... }
public void Walk() { ... }
public abstract void DoSOund();
public Image TakePhoto();
}
public class Cat : Animal // no need to repeat IPhotoTaking
{
public override void DoSound() { ... }
}
public class Dog : Animal
{
public override void DoSound() { ... }
}
public abstract class Building :IPhotoTaking
{
public Image TakePhoto();
}
public class House : Building
{
}
public class Museum : Building
{
}
Now having this list we can use polymorphism like that:
var animals = new List<Animal>();
foreach ( var animal in animals )
animal.DoSound();
Also without polymorphism and because C# does not support true polymorphism with the diamond operator yet applied on List<> here, we can use the interface like that:
var items = new List<IPhotoTaking>();
foreach ( var item in items )
item.TakePhoto();
Remark: if taking a photo may be different for each types, we can set it virtual to specialize its implementation in each.
OOP Basic Principles
What is abstraction in C#?
How to choose between public, private and protected access modifier?
Association, Composition and Aggregation
What is polymorphism?
What is the difference between an interface and a class?
About the lack of true generic polymorphism and the missing diamond operator in C#

Looking for other ways to hide abstract inheritance method from a subclass?

I want the inherited method Invoke() to be hidden from the final subclass ConcreteExecutablePlugin.
Whole situation:
public abstract class PluginBase
{
public abstract void Invoke(IDictionary parameters);
}
public abstract class JobPlugin : PluginBase
{
protected void CheckParameter(){//....}
public bool IsActive(){//....}
}
public class ConcreteJobPlugin : JobPlugin
{
public override void Invoke(IDictionary parameters){//...}
}
public abstract class ExecutableJobPlugin : JobPlugin
{
protected abstract void Initialize(IDictionary parameters);
public sealed override void Invoke(IDictionary parameters)
{
//final realization of Invoke() method
}
}
public class ConcreteExecutablePlugin : ExecutableJobPlugin
{
//here i want method Invoke() has been already hiden
//!!!OR use base.Invoke() better?
protected override void Initialize(IDictionary parameters)
{
//concrete plugin initialization
}
}
I have found only one solution. Now, I'm using sealed for this. What do you think about this solution?
Do you know another ways to hide abstract inheritance method?
Re: Visibility
A public method signals the design intention that it is visible to all - if this isn't the designed intention, change the method's visibility accordingly, e.g. protected (but obviously any subclass has access), or if all classes which are allowed to use Invoke are in the same assembly, then Invoke can be declared protected internal abstract.
Re: Sealed
As per Lasse's point, sealed override methods will disrupt the polymorphic virtual / override chain during inheritance, but still, it can not change the fact that the base method is public. However, applying sealed to a class will prevent other classes from inheriting it all, thus restricting access to all protected methods.
Solution
I believe the underlying problem relates to over-using inheritance - seemingly you want to inherit functionality to obtain reuse, but at the same time need to restrict access at some point in the chain to an "untrustworthy" subclass. Other than the point about making methods internal + moving all "trustworthy" subclasses into the base class assembly, you will have little control when using a full chain of subclasses.
I believe that decoupling your hierarchy via interfaces, and applying the principle of composition over inheritance, will better achieve what you are after. In fact, the Decorator pattern looks to be an option here.
You can also set the 'trustworthiness' boundary by making the 'last trustworthy' subclass (ExecutableJobPlugin) as sealed *.
Example:
// Expose just what is visible to your final Subclass on the interface
public interface IExecutableJobPlugin
{
bool IsActive { get; set; }
void CheckParameter();
void Initialize(IDictionary parameters);
}
// Sealed will prevent other classes from inheriting this class.
public sealed class ExecutableJobPlugin : JobPlugin, IExecutableJobPlugin
{
// Default implementation. NB, not abstract
public void Initialize(IDictionary parameters) {}
// This isn't visible on the interface
protected override sealed void Invoke(IDictionary parameters)
{
//final realization of Invoke() method
}
}
public class ConcreteExecutablePlugin : IExecutableJobPlugin
{
// Compose a decoupled IExecutableJobPlugin instead of direct inheritance
private readonly IExecutableJobPlugin _wrappedJobPlugin;
public ConcreteExecutablePlugin(IExecutableJobPlugin wrapped)
{
_wrappedJobPlugin = wrapped;
}
// Invoke() isn't on the interface so cannot be accessed here
public void Initialize(IDictionary parameters)
{
// Call 'super' if needed.
_wrappedJobPlugin.Initialize(parameters);
//concrete plugin initialization code here ...
}
public bool IsActive
{
get { return _wrappedJobPlugin.IsActive; }
set { _wrappedJobPlugin.IsActive = value; }
}
public void CheckParameter()
{
_wrappedJobPlugin.CheckParameter();
}
}
Notes
Because ConcreteExecutablePlugin is no longer a subclass of PluginBase, if you change method PluginBase.Invoke to protected, that ConcreteExecutablePlugin will have no access to it (aside from hacks like reflection).
All 'reused' methods and properties needed from the composed (née base) class ExecutableJobPlugin need to be rewired in the ConcreteExecutablePlugin. Although somewhat tedious, it does allow for additional interception, e.g. cross cutting concerns like logging.
The ExecutableJobPlugin class may no longer be abstract, since an instance will be needed for the composition to work.
Ideally, the ExecutableJobPlugin should be injected externally (as opposed to new within)
Decoupling via interfaces improves the testability of your class hierarchy
* Sealing ExecutableJobPlugin won't however prevent others from subclassing public superclasses like PluginBase and JobPlugin. To prevent this, you could keep all the base classes in the same assembly and mark these as internal, or continue to apply the interface decoupling / Decorator pattern instead of inheritance across the entire chain.
The pattern could obviously be repeated for multiple levels of your class hierarchy, and the interface segregation principle should be applied to ensure that your interfaces remain lean and focused.
It is impossible to hide public methods in derived classes. The whole point of public is that the method is accessible in the base class and any descendants of that class.
You could try using protected, and then simply have a public method like Initialize in your derived plugins, or you could try using internal (although that would probably not be preferable).

Is it not the waste of time to create abstract classes?

I am so confused about the abstract classes I know it is not a question related to programing problem.But this is the only place I can find solution for this.
As everybody know that abstract classes cannot be instantiated and you cannot implement anything in these classes. We can just derive these classes and can do implementation in derived classes. So my question is this:
If we have to implement logic in derived classes and we have to use complete function and classes in derived class then why we create abstract classes?
Can anybody give me a clear explanation for this? If there is any good example then please tell me
When you use an abstract class you have some implementation in the abstract class, but leave bits that are specific to a derived class as abstract. For example, I might define an abstract class for all shapes:
abstract class Shape
{
public int Sides{get;protected set;}
public abstract int CalculateArea();
}
All shapes have a particular number of sides, so that can go into the general case (ie Shape). The calculcation of the area depends on the type of shape (triangle, square etc) so if belongs in the derived class. However, I'd like users of my class hierarchy to be able to call CalculateShape from any Shape instance.
How I create a derived class and override CalculateLength:
class Square : Shape
{
public Square(int sideLength)
{
this.Sides = 4;
this.SideLength = sideLength;
}
public int SideLength{get;private set;}
public override int CalculateArea()
{
return this.SideLength * this.SideLength
}
}
Note that I haven't reimplemented all of Shape in Square, I have only implemented the Square specific bits.
According to MSDN,
An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.
The above are all the technical explanation, in layman style it's like creating a blueprint that provide info what all things it can do, and all the derived classes will provide there own process how to do that.
For example, we can think of Driver and we know there are many driver types like auto-rickshaw driver, truck driver, tractor driver etc. but all have a common denominator functionality that is Driving but each of Driving process will be different, thus
Driver: abstract class with Driving function
Auto-RickshawDriver: Derived class extending Driver class
Your question,
If we have to implement logic in derived classes and we have to use complete function and classes in derived class then why we create abstract classes?
Just because we want to define some common functionality, that every other class has to abide to be member of it. In general term creating groups based on functionality, i.e. we can say if that class belong to a group we are damn sure that those common functionality of that group will be present.
Abstract classes will contain common incomplete implementation which can then be reused from multiple derived classes.
protected methods inside it can only be called from inside the derived classes.
abstract methods need to be implemented in derived classes.
virtual methods can be ocerriden in derived classes
In .NET framework you can find many examples of such abstract classes, e.g. System.IO.Stream.
The code using all those classes can refer to them using their common public interface of Stream, not having to know which concrete Stream implementation it uses.
Just to correct a minor detail, abstract classes can be partially abstract or fully abstract, depending on whether they are partially implemented (in which case we commonly call them abstract classes) or not implemented at all and have no member variable (in which case we commonly call them interfaces).
They are many uses for abstract classes, most of them implying the ability to extend behaviour of code without modifying this code.
Let's suppose that you want to write a program that reads data from the keyboard and writes it to the screen. (I'll use C# for the code, because it's slightly shorter than C++)
void Copy() {
int c;
while((c = Console.Read()) != -1) {
Console.Write(c);
}
}
Now, the requirements change. You want to be able to read from a file instead of the keyboard, depending on a variable.
TextReader reader;
void Copy(bool readFromFile) {
int c;
while((c = ReadNextChar(readFromFile)) != -1) {
Console.Write(c);
}
}
int ReadNextChar(bool readFromFile) {
if(readFromFile) {
return reader.Read();
} else {
return Console.Read();
}
}
Now, you want to be able to read from the network. The bool becomes an enum, the if/else becomes a switch/case etc. etc.
enum ReadMode { FROM_CONSOLE, FROM_FILE, FROM_NETWORK };
TextReader fileReader;
TextReader networkReader;
void Copy(ReadMode readMode) {
int c;
while((c = ReadNextChar(readMode)) != -1) {
Console.Write(c);
}
}
int ReadNextChar(ReadMode readMode) {
switch(readMode) {
case FROM_CONSOLE:
return Console.Read();
case FROM_FILE:
return reader.Read();
case FROM_NETWORK:
return networkReader.Read();
default:
return -1;
}
}
And this can go on. And the same requests may occur for the writing. The problem with this program is that it explicitly lists all the ways you can read from a file. To read from another source, you have to modify the code (add a member to the enum ReadMode and add a case in ReadNextChar. You may deem this OK if you have access to the source code, but if it's an external library, you may deem crappy this way of doing because you can not extend this wonderful copy library.
Now meet abstract classes. What if you abstracted all the sources into a single Source concept, because after all, all you need is to ask the source for an int. So let's write this abstract concept.
interface Source {
int ReadNextChar();
}
And all three implementations:
class KeyboardSource : Source {
int ReadNextChar() {
return Console.Read();
}
}
class FileSource : Source {
TextReader reader;
FileSource(string path) {
reader = new StreamReader(path);
}
int ReadNextChar() {
return reader.Read();
}
}
class NetworkSource : Source {
TextReader reader;
NetworkSource (string url) {
reader = new StreamReader(path);
}
int ReadNextChar() {
return reader.Read();
}
}
And implement the copy function:
void Copy(Source source) {
int c;
while((c = source.ReadNextChar()) != -1) {
Console.Write(c);
}
}
Now any source type you want to add, you just have to implement a new derivative of Source, without modifying existing code. The Copy program remains correct and untouched, so do the existing derivatives of Source.
This is called polymorphism. If you look at the dependencies of the Copy, they don't include code concerning either files, network, or user interface. It can be packaged in a library, allowing users to extend the types of sources from which it can read.
Hope it's clear. The same can be done for the writing part.
Regard this example:
abstract class A
{
// forces subclasses to implement
abstract void method1();
virtual void method2()
{
// some common logic
// that sublcasses can
// modify
}
protected void method3()
{
// some common logic
}
}
class B : A
{
void method1()
{
// needs to be implemented
}
override void method2()
{
// optional: e.g. something added
base.method1();
}
}
class C : A {
//...
}
No you can specify common logic in the base class, as well as define abstract methods that every subclass will have. So your baseclass works like an interface. You can call method1() to every instance of B and C.
So: No! It's absolutely no waste of time ;-).
It's not,
Assume you have a base class
class Foo{
public String getGreetingMessage(){
return "Hello " + getName();
}
public abstract String getName();
}
and you have a derived class
class Bar extends Foo{
public String getName(){
return "MeMamo";
}
}
class Boo extends Foo{
public String getName(){
return "Boo";
}
}
And in another class, I call the method from derived,
Bar b = new Bar();
System.out.println(b.getGreetingMessage()); // Hello MeMamo.
Boo boo = new Boo();
System.out.println(boo.getGreetingMessage()); // Hello Boo;
I don't need to write the base method all over again.
Assume that operation for another derived class.

Change/Swap base class at runtime with another base class

Sounds like silly idea but I was wondering if it's possible somehow.
Is it possible to change the base class of a derived class at runtime? Of course, there are lot of ifs and buts and the the question of why would someone do it and its a bad design probably and all that.
Keeping all those aside (even though they might be perfectly valid), let's say, just for kicks or to show your nerdiness, is it possible in C# or any language for that matter?
So something like:
public class baseOriginal {
public string justAProperty;
}
public class baseSwapped {
public int sillyNumber;
}
public class derivedClass : baseOriginal {
public bool iAmDumb;
}
void Main() {
baseOriginal derived = new derivedClass ();
Console.WriteLine(derived.justAProperty);
baseSwapped derivedSwapped = (??);
Console.WriteLine(derivedSwapped.sillyNumber);
}
It isn't possible in C#. Probably what you want is more of a prototype-based solution commonly found in dynamic languages like JavaScript where you can "extend" the functionality of the object by adding to how it's defined.
But to accomplish what your code hints at doing, you can have the swappable classes inherit from a common ancestor class. That way you can assign instances of each to their decendents.
public class baseClassAncestor{
}
public class baseOriginal:baseClassAncestor {
public string justAProperty;
}
public class baseSwapped:baseClassAncestor {
public int sillyNumber;
}
public class derivedClass : baseOriginal {
public bool iAmDumb;
}
You can do one time base class swap by loading different assemblies that implement base class BEFORE using derived class. But this approach will not make your exact code working as you will not be able to compile that - but moving access to methods of different base classes to separate functions could be made working.
You add UnionBase class that contains all possible methods/properties from all base classes so you can compile your Main code against the assembly with this class. Than at run time you load assembly that has contains your particular base class.
Usual warning: You need to have very good reasons and understanding for going this route. I.e. existing external code is a reason to consider such approach.
"Don't do it at home, performed on a closed course by trained professional".
One more possible workaround could be implemented using some AOP solution that is based on compile-time weaving, i.e. PostSharp, which is able to seamlessly inject new methods and interfaces to existing types as well as modify (intercept) existing ones.
There is actually a good reason where you may want to swap the base class. Let say you want to modify the base class but you don't wan't to perturb the current code base as it is shared among other teams. Let say there are 10+ derived class that inherits from base. You could create 10+ custom derived classes to override the base class but that is a lot of work. Here is what you do. The key to the problem is to create an interface and a base proxy class.
class Program
{
static void Main(string[] args)
{
IActionable action = new Derived<Base1>();
action.open();
action = new Derived<Base2>();
action.open();
}
}
// Proxybase is a fake base class. ProxyBase will point to a real base1 or
// base2
public class Derived<T>:ProxyBase,IActionable
{
public Derived():base(typeof(T))
// the open function is not overriden in this case allowing
// the base implementation to be used
}
// this looks like the real base class but it is a fake
// The proxy simply points to the implementation of base1 or base2 instead
public abstract class ProxyBase: IActionable
{
IActionable obj;
public ProxyBase(Type type,params object[] args)
{
obj = (IActionable)Activator.CreateInstance(type,args);
}
public virtual void open()
{
obj.open();
}
}
// notice base1 and base2 are NOT abstract in this case
// consider this the original implementation of the base class
public class Base1: IActionable
{
public virtual void open()
{
Console.WriteLine("base1 open");
}
}
// here base2 acquired the functionality of base1 and hides base1's open
function
// consider this implementation the new one to replace the original one
public class Base2: Base1, IActionable
{
public new virtual void open()
{
Console.WriteLine("base2 open");
}
}
public interface IActionable
{
void open();
}
The result would be as follows
base1 open
base2 open
UPDATE:
Although this answer works, the reality is that inheritance introduces coupling which makes this exercise difficult at best. Also, in a practical scenario, your requirements may lead you to want to derive from multiple base class which is not possible in c#. If you want to interchange the base class you are best to use the bridge design pattern (which in fact avoids inheritance altogether thus avoiding the coupling).
The closest thing I can think of is the following:
http://msdn.microsoft.com/en-us/library/dd264736.aspx
static void Main(string[] args)
{
ExampleClass ec = new ExampleClass();
// The following line causes a compiler error if exampleMethod1 has only
// one parameter.
//ec.exampleMethod1(10, 4);
dynamic dynamic_ec = new ExampleClass();
// The following line is not identified as an error by the
// compiler, but it causes a run-time exception.
dynamic_ec.exampleMethod1(10, 4);
// The following calls also do not cause compiler errors, whether
// appropriate methods exist or not.
dynamic_ec.someMethod("some argument", 7, null);
dynamic_ec.nonexistentMethod();
}
class ExampleClass
{
public ExampleClass() { }
public ExampleClass(int v) { }
public void exampleMethod1(int i) { }
public void exampleMethod2(string str) { }
}
I have no idea if the dynamic language runtime can do what you want it to do.
Closest you could get would be to
derive from both types by defining at
least one as an interface, then
casting derived from one to the other.
I would have to agree, based on the example this suggestion would satisfy what he wants to do, it also is a better design then what he actually wants to do.
Closest you could get would be to derive from both types by defining at least one as an interface, then casting derived from one to the other.

Categories