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?
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With