I was happy programming with (generic) constraints which overtook the limitations in C++ templates. However, constraints need to be less restrictive. What is that? Let us say I want a helper method that checks a condition and throws an exception if the check failed. So that would be...
void TestCondition(bool condition, string msgText)
{
if (!condition)
{
throw new Exception(msgText ?? "Unknown Error");
}
}
I like it; it is cute. However, not at all times would the caller be happy with throwing System.Exception. Since the above method can be used in a wide variety of situations, it would make sense for the caller to specify the type of exception he would like to throw. It would be classic if the above is made generic taking type T and constraining it be to a derivate of System.Exception. Sounds great and so…
void TestCondition2<T>(bool condition, string msgText) where T : Exception
{
if (!condition)
{
throw new T(msgText ?? "Unknown Error");
}
}
The above code is dream still; it will result in a compilation error. Although generics offers the constraint that T should be a derivate of System.Exception, it does not relax it specifying the constructor it would like to use from T; in other words, there is constraint mandating T to expose a default constructor but none other. So we cannot offer the above facility with elegance (or performance?). There is the ugly way. How?
void TestCondition3(bool condition, Exception ex)
{
if (!condition)
{
throw ex;
}
}
Seems good? Partly No. If TestCondition2 was possible, the exception object(s) would be created only if the condition failed, while TestCondition3 meeting our purpose creates exception objects irrespective of the condition; and gets thrown if the condition fails.
So when are (generic) constraints going to be relaxed? C# 5.0?