Reputation: 5901
So I have a method which looks something like this
public void Register<T>(TimeSpan interval, ILogger logger) where T : ISchedule
{
_schedules.Add(new Schedule<T>(interval, logger));
}
I want to create a new Schedule with the T provided to the Register Method.
internal class Schedule<T> : IDisposable where T : ISchedule, new() {}
Here I get the following error:
'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Schedule<T>'
Is this behavior even possible or is there anything I am doing wrong?
Upvotes: 1
Views: 55
Reputation: 5105
You need to apply the where T : ISchedule, new()
constraint you specified on the Schedule<T>
class to the Register
method as well:
public void Register<T>(TimeSpan interval, ILogger logger) where T : ISchedule, new()
{
_schedules.Add(new Schedule<T>(interval, logger));
}
Consider the following two classes which implement the ISchedule
interface.
public class Schedule1 : ISchedule
{
public Schedule1() { }
}
public class Schedule2 : ISchedule
{
public Schedule2(string foo) { }
}
The Schedule<T>
class has a generic type constraint where T : ISchedule, new()
meaning only those types implementing ISchedule
and containing a parameterless constructor can be used as the type parameter. Therefore, it is illegal to specify a Schedule<Schedule2>
since Schedule2
does not contain a parameterless constructor.
If we do not apply the same type constraint to the Register
method, we can call that method with both Schedule1
and Schedule2
. As Schedule2
does not conform to Schedule<T>
's type constraint, we now have a problem ('T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Schedule<T>'
) that can be solved by applying the same constraint of Schedule<T>
to the Register
method.
Further reading: Constraints on Type Parameters on Microsoft Docs.
Upvotes: 2