I want to use two classes with identical external interfaces inter-changeably in my code. Basically I have two classes and both have the same functions and everything but do different things in a different way... I want to, from
an external class select which class I'm going to use at Run-Time.
I don't however want to use a massive branch in order to select which class is used.
Basically from the external classes point of view it should always be calling the same class but in reality it is calling one of the classes based on earlier conditions.
Can anyone help me with this? Is there a way to define a generic class that can act like both classes at run time?
A simple analogy is if I had a listBox that listed Class1 and Class2, if I selected ‘Class2’, the program would then use Class2 instead of Class1 which is the default.. but I want to do it without large branches.
-
-
Derive Class1 and Class2 from a common base class, Class3 and then use virtual functions to implement the specifics of the two classes.
You listbox then just calls methods of Class3 and these evaluate to the appropriate subclass at runtime. -
Would a basic example be possible? I would much appreciate it.

-
Thanks, that is exactly what I need. Thanks for your help and to AndyC.

-
using System;
using System.Collections.Generic;
using System.Text;
namespace InterfaceExample
{
class Program
{
static void Main(string[] args)
{
IClass Bar;
string input = Console.ReadLine();
switch (input)
{
case "Class1":
Bar = new Class1();
break;
case "Class2":
Bar = new Class2();
break;
default:
return;
}
Bar.Foo();
Console.ReadLine();
}
}
interface IClass
{
string Foo();
}
class Class1 : IClass
{
public string Foo()
{
Console.WriteLine("1");
return "1";
}
}
class Class2 : IClass
{
public string Foo()
{
Console.WriteLine("2");
return "2";
}
}
}
-
ahhh.. the wonders of runtime method binding and inheritence
Jake -
GooberDLX wrote:ahhh.. the wonders of runtime method binding and inheritence
Jake
Yeah, it's completely brilliant.
It took me a while to "get" OOP, having come from a Pascal/Assembler background but it really is incredibly powerful. -
What's faster? Using interfaces to call methods, or a base class?
-
Either one will require the dynamic method binding that I described, at least one would expect it to happen that way.
Unless you tested, I would guess that it wouldn't be noticable.
Jake
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.