Reputation: 2923
Say I have the following
public interface IInterval<T>
{
T Start { get; }
T Stop { get; }
}
public class DateTimeInterval : IInterval<DateTime>
{
private DateTime _start;
private DateTime _stop;
public DateTimeInterval(DateTime start, DateTime stop)
{
_start = start; _stop = stop;
}
public DateTime Start
{
get { return _start; }
}
public DateTime Stop
{
get { return _stop; }
}
}
public class SortedIntervalList<T>
where T : IInterval<T>, IComparable<T>
{
}
If I were to now try to instantiate the container
var test = new SortedIntervalList<DateTimeInterval>();
I get a compilation error
The type 'Test' cannot be used as type parameter 'T' in the generic type or method
TestContainer<T>
. There is no implicit reference conversion from 'Test' toITest<Test>
.
Why is this?
Note on edit history
For clarity, classes for the original question are included below
public interface ITest<T>
{
int TestMethod();
}
public class Test : ITest<bool>
{
public int TestMethod()
{
throw new NotImplementedException();
}
}
public class TestContainer<T>
where T : ITest<T>
{
}
Upvotes: 2
Views: 114
Reputation: 157038
Because you expect your T
in TestContainer<T>
to be ITest<T>
. that doesn't make sense. I think you meant :
public class TestContainer<C, T>
where C : ITest<T>
{
}
For your updated code in your question:
public class SortedIntervalList<C, T>
where C : IInterval<T>, IComparable<T>
{ }
With:
test = new SortedIntervalList<DateTimeInterval, DateTime>();
Upvotes: 2
Reputation: 887767
where T : ITest<T>
Your class inherits ITest<bool>
, which is not ITest<T>
for your T
(Test
).
As the error is trying to tell you, that does not meet your generic constraint, so you can't do that.
Upvotes: 4