I have a situation where I have a method that takes a couple of overloads. I have a fairly common scenario where if some condition is true, I call one of the overloads, otherwise I call something else. I decided to try to be clever and refactor the common code into a single generic method that would take an object and a condition, and call the overloaded method or otherwise call the common code.
A much simplified example of the code:
/// <summary>
/// Dummy interface
/// </summary>
public interface ITest1
{ }
/// <summary>
/// Dummy interface
/// </summary>
public interface ITest2
{ }
/// <summary>
/// Generic Class
/// </summary>
public class GenericClass
{
/// <summary>
/// First overload
/// </summary>
/// <param name="test1"></param>
public void TestMethod(ITest1 test1)
{ }
/// <summary>
/// Second overload
/// </summary>
/// <param name="test2"></param>
public void TestMethod(ITest2 test2)
{ }
/// <summary>
/// method with common logic
/// </summary>
/// <typeparam name="TInterfaceType">
/// Type of the test object
/// </typeparam>
/// <param name="test">
/// Test object to pass to the method.
/// </param>
public void ConditionallyCallTest<TInterfaceType>(
TInterfaceType test, bool someLogic)
{
if (someLogic)
{
this.TestMethod(test);
}
else
{
// .. Perform Common operations here
}
}
}
Ignoring the fact that this doesn't do anything, if you compile this code segment, you will get a compiler error that it can't convert TInterfaceType to ITest1.
I was hoping for the compiler to wait until I specified the type to do the type checking, so:
GenericClass g = new GenericClass();
// We have an overload, so this is OK:
g.ConditionallyCallTest<ITest1>(test1);
// We have an overload, so this is OK:
g.ConditionallyCallTest<ITest2>(test2);
// Compiler error, no overload available:
g.ConditionallyCallTest<UnknownType>(obj);
Is it possible to do something like this using C#?
I also tried to use the where clause to specify the allowable types, but I couldn't figure out how to get the where clause to specify an either/or relationship between the specified types, only an AND relationship.
EDIT
As I mentioned in the comments below, I was attempting to avoid having to create matching overload methods, so are there any other suggestions to solve this problem, or am I limited by the language here?