C# casting generic parameter to interface

c#, casting, generic-constraints, generics, types

Solution

The `is` and `as` operators only compile for types that the compiler knows can be `null` (nullable value types or reference types).

You can try a call to IsAssignableFrom:

public int adaptiveFoo<T>()
{
  if (typeof(InterFoo<T>).IsAssignableFrom(typeof(T))
    return specialFoo<InterFoo>();
  return regularFoo<T>();
}

** Update to reflect changes in question **

Type constraints are, unfortunately viral, in order for your method to compile (when keeping with strict type checking from the compiler) you would need the constraint to be added to this method also. However, reflection can circumvent this restriction:

Your method would be:

public InterFoo<T> adaptiveFoo<T>()
{
  if (typeof(InterFoo<T>).IsAssignableFrom(typeof(T))
  {
    var method = typeof (Class1).GetMethod("specialFoo");
    var genericMethod = method.MakeGenericMethod(typeof(T));
    return (Interfoo<T>)method.Invoke(this, null);
  }

  return regularFoo<T>();
}

Problem

I need help with casting generic paremetrs down to an interface. I have prebaked code like this: ``` public interface InterFoo<T> {...} public InterFoo<T> specialFoo<T>() where T : InterFoo<T> {...} public InterFoo<T> regularFoo<T>() {...} ``` and i want to implement something like this ``` public InterFoo<T> adaptiveFoo<T>() { if (T is InterFoo<T>) return specialFoo<T as InterFoo>(); return regularFoo<T>(); } ``` at this point I cant find any solution so anything would be helpful, thanks. EDIT: originally the functions had returned an int but that has a simpler solution that is incompatible with the code's intended purpose, the functions have been changed to request a generic type.

Original source