ILoggable

A place to keep my thoughts on programming

June 7, 2007 .net

Generic return values and explicit casting

Came across an artifact with generics that confused me. Let’s say you had an interface IFoo:

  public interface IFoo
  {
    [...]
  }

and a class Foothat implements IFoo:

  public class Foo : IFoo
  {
    [...]
  }

then a given method returning IFoo doesn’t have to explicitly cast Foo to the interface:

  public IFoo Foo()
  {
    return new Foo();
  }

So, I figured that the same would be true for a generic method returning T with a constraint to IFoo. However, it seems that the constraint is not considered for implicit casting to T. So you have to explicitly cast Foo to IFoo and then cast that to T:

  public T Foo<T>() where T : IFoo
  {
    return (T)(IFoo)new Foo();
  }

That just seems a bit strange to have to do.

Leave a comment