Jack2019
Jack2019

Reputation: 275

using "where" keyword to limit the generic candidates to be a class, which is also a generic

Suppose I have a series

public class TimeSeries<T,K>

and I want to construct a class which has a list member that can store TimeSeries as element, so I use:

public class TimeSeriesSet<M> where M: TimeSeries<T, K>

I wonder what would be the correct syntax for that ?

Upvotes: 1

Views: 69

Answers (2)

Tyree Jackson
Tyree Jackson

Reputation: 2608

Luaan's answer covers two of the ways to structure your code. However, there is a variation that you could use. It looks as though TimeSeriesSet is one way coupled to TimeSeries both in name and via the type parameters. I wonder if perhaps, one of the following wouldn't make more sense in your application:

Without the descendant constraint:

public class TimeSeries<T, K>
{
    public class Set
    {
        public TimeSeries<T, K> SomeField;
    }
}

Or with the descendant constraint:

public class TimeSeries<T, K>
{
    public class Set<M> where M : TimeSeries<T, K>
    {
        public M SomeField;
    }
}

This has the added advantage of DRYing up the type parameter declarations and more clearly models that TimeSeriesSet<T, K, M> is dependent on TimeSeries<T, K> and its type parameters by making it TimeSeries<T, K>.Set<M>.

Upvotes: 1

Luaan
Luaan

Reputation: 63732

You can do something like this:

public class TimeSeriesSet<T, K>
{
  public TimeSeries<T, K> SomeField;
}

No need to use constraints at all. Don't use generic type arguments if you're not actually going to use them ;)

The only reason why you'd want to add another type argument would be if you wanted some explicit descendant of TimeSeries<T, K>. In that case, just add it as yet another type argument:

public class TimeSeriesSet<M, T, K>
  where M: TimeSeries<T, K>
{
  public M SomeField;
}

In general, genericity tends to propagate. If you need something generic over something generic, you need two generic type arguments. Thankfully, type inference usually works. Usually.

Upvotes: 5

Related Questions