I have two function that do the exact same thing in two different ways. Each uses a different class to accomplish the task:
void functionA()
{
ClassA a = new ClassA();
a.doWork();
}
void functionB()
{
ClassB b = new ClassB();
b.doSomething();
}
this is all in a self contained HttpHandler that can be dropped in any project and work – At least thats the goal. FunctionA would be the preferred way of doing things, FunctionB is a fallback. ClassA might not exist in a given project, ClassB will always exist.
Is there a way at runtime to detect is ClassA exists an use functionA and if not use fcuntionB. Also is there a way to compile this if ClassA doesn’t exist? Can I do this with pre-processor stuff (i.e. can I tell at compile time which to include?)
Typically, situations like this are much better handled via Inversion of Control than trying to determine the existence of a class.
Instead of looking for “ClassA” and “ClassB”, it would be a better option to provide 2 interfaces that could be implemented. You could then use Dependency Injection to attempt to inject an instance of
IInterfaceA, and if it fails, use an instance ofIInterfaceBinstead.A good articles to read might be Martin Fowler’s article on IoC. Also, you may want to look at the Managed Extensibility Framework (now included in .NET 4) which makes this very easy in C#.