C#: Calling a generic from a generic with surprises


I am currently working on C# wit generics. The base concept seems to be the same as in C++ ( which I really like honestly spoken ).
And I tried to use specialization. There was a class which needs to deal with special data types. And for some special cases you need a type-specific semantic, because bool cannot be added for example. So I tried to do something like this:

public class MyGeneric<T> {
  T mValue;
  public MyGeneric<T>() {}
  public OnMethod( T v ) {
    mValue = v;
  }
  public OnMethod(bool v ) {
    mValue = !v;
  }

  static main() {
    MyGeneric<int> i = new MyGeneric<int> i();
    i.OnMethod(1); // Will call the generic method
    MyGeneric<bool> b = new MyGeneric<bool> i();
    b.OnMethod(true); // Will call the specialized method for bool
  }
}

Looks greate, I thought. problem soled I thought. Let’s integrate it into your application and continue to live a happy life again I thought. I was so wrong …

Because when calling a generic method from a generic method this specialization will not work:


public class MyCaller<T> {
  MyGeneric<T> mClassToCall;
  ...
  public void MethodCaller<T>( T v ) {
    mClassToCall.OnMethod( v );
  }
}
public class MyGeneric<T> {
  T mValue;
  public MyGeneric<T>() {}
  public OnMethod( T v ) {
    mValue = v;
  }
  public OnMethod(bool v ) {
    mValue = !v;
  }

  static main() {
    MyCaller<bool> boolCaller = new MyCaller<Bool> i();
    boolCaller.MethodCaller(true); // Will call the generic method public OnMethod( T v )
  }
}

This will not call the specialization. You need to add special traits to deal with this situation.

The solution is simple: use a type trait to detect which specialization is the right one for you and do the switch during runtime.