How to use abstract base class properly C# - c#

Hi I'm creating a geometry library in C#...
I have an abstract class shape.
I have defined a class vector (also representing (x,y) points).
I would like to use a variety of geometrical objects, curves, lines, arcs, paths etc
To do this I've defined an abstract Segment class and derived a number of classes e.g. LineSegment (see below), CurveSegment, ArcCircleSegment, BezierCurveSegment, HalfInfiniteLine etc.
I've also defined a class Path (NOT abstract) which is intended to represent a number of segments joined together (like what you might get from a drawing application). In this i include a List member of Segments (List<Segment>).
Then i wish to derive classes from Path, the key example being LinePath which should contain only LineSegments. The problem i have is i'd like to be able to call the get property on a LinePath object assuming it'll return a LineSegment. Is this possible without explicitly casting each time?
I want to avoid making Path abstract as i might have a path of multiple Segment types.
public class LineSegment : Segment
{
private vector m_start;
private vector m_end;
private vector m_vector;
public vector Start
{
get { return m_start; }
set { m_start = value; }
}
public vector End
{
get { return m_end; }
set { m_end = value; }
}
public vector Vec
{
get { return m_vector; }
set { m_vector = value; }
}
public double Length()
{
return Vec.length();
}
public LineSegment(vector v0, vector v1):base()
{
this.Start.x = v0.x;
this.Start.y = v0.y;
this.End.x = v1.x;
this.End.y = v1.y;
this.Vec = this.End - this.Start;
}
}

If I understand what you want correctly, you can do something like this:
Make your path class generic
public class Path<T> where T : Segment
{
private IList<T> segments = new List<T>();
public IList<T> Segments { get { return this.segments; } }
}
You can then create your LinePath object
public class LinePath : Path<LineSegment>
{
}
that way you can ensure that all segments in your LinePath.Segments are LineSegments while still being able to re-use the Path class for any operations which act against a Segment.

You can redefine the Path property on your derived classes. LinePath can have:
public new List<LineSegment> Segments
{
get
{
return (List<LineSegment>)base.Segments;
}
}
This way you will enforce the correct type usage.

When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.
For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.
–> 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.
Use an abstract class
When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.)
Use an abstract class to define a common base class for a family of types.
Use an abstract class to provide default behavior.
Subclass only a base class in a hierarchy to which the class logically belongs.

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#

Workaround for Multiple Inheritance in 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.

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