Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic constraints and interface implementation/inheritance

Tags:

c#

generics

Not entirely sure how to phrase the question, because it's a "why doesn't this work?" type of query.

I've reduced my particular issue down to this code:

public interface IFoo
{
}

public class Foo : IFoo
{
}

public class Bar<T> where T : IFoo
{
    public Bar(T t)
    {
    }

    public Bar()
        : this(new Foo()) // cannot convert from 'Foo' to 'T'
    {
    }
}

Now, the generic type T in the Bar<T> class must implement IFoo. So why does the compiler give me the error in the comment? Surely an instance of Foo is an IFoo, and can therefore be passed around as a representative of the generic type T?

Is this a compiler limitation or am I missing something?

like image 819
Matt Hamilton Avatar asked Jan 07 '09 00:01

Matt Hamilton


1 Answers

You could also have a Fiz that implements IFoo that is not related to Foo in any other way:

public interface IFoo
{
}

public class Foo : IFoo
{
}

public class Fiz : IFoo
{
}

Foo foo = new Foo();
Fiz fiz = foo; // Not gonna compile.

What you want is probably more like:

public class Bar<T> where T : IFoo, new()
{
    public Bar(T t)
    {
    }

    public Bar()
        : this(new T()) 
    {
    }
}

So you can have

Bar<Foo> barFoo = new Bar<Foo>();
Bar<Fiz> barFiz = new Bar<Fiz>();
like image 153
Andrew Kennan Avatar answered Oct 13 '22 04:10

Andrew Kennan