Imlpementations of an Interface with Different Types?
Posted
by
b3njamin
on Stack Overflow
See other posts from Stack Overflow
or by b3njamin
Published on 2011-03-04T15:02:56Z
Indexed on
2011/03/04
15:25 UTC
Read the original article
Hit count: 218
Searched as best I could but unfortunately I've learned nothing relevant; basically I'm trying to work around the following problem in C#...
For example, I have three possible references (refA, refB, refC) and I need to load the correct one depending on a configuration option. So far however I can't see a way of doing it that doesn't require me to use the name of said referenced object all through the code (the referenced objects are provided, I can't change them). Hope the following code makes more sense:
public ??? LoadedClass;
public Init()
{
/* load the object, according to which version we need... */
if (Config.Version == "refA")
{
Namespace.refA LoadedClass = new refA();
}
else if (Config.Version == "refB")
{
Namespace.refB LoadedClass = new refB();
}
else if (Config.Version == "refC")
{
Namespace.refC LoadedClass = new refC();
}
Run();
}
private void Run(){
{
LoadedClass.SomeProperty...
LoadedClass.SomeMethod(){ etc... }
}
As you can see, I need the Loaded class to be public, so in my limited way I'm trying to change the type 'dynamically' as I load in which real class I want. Each of refA, refB and refC will implement the same properties and methods but with different names. Again, this is what I'm working with, not by my design.
All that said, I tried to get my head around Interfaces (which sound like they're what I'm after) but I'm looking at them and seeing strict types - which makes sense to me, even if it's not useful to me.
Any and all ideas and opinions are welcome and I'll clarify anything if necessary. Excuse any silly mistakes I've made in the terminology, I'm learning all this for the first time. I'm really enjoying working with an OOP language so far though - coming from PHP this stuff is blowing my mind :-)
© Stack Overflow or respective owner