I have built myself a generic collection class which is defined like this.
public class StatisticItemHits<T>{...}
This class can be used with int
and string
values only. However this
public class StatisticItemHits<T> where T : string, int {...}
won't compile. What am I doing wrong?
Object, you'll apply constraints to the type parameter. For example, the base class constraint tells the compiler that only objects of this type or derived from this type will be used as type arguments.
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.
This generic object will still work fine with int but declaring int as a generic type is wrong. Generics allow only object references not the primitives.
The type restriction is meant to be used with Interfaces. Your sample suggests that you want to allow classes that inherit from int and string, which is kinda nonsense. I suggest you design an interface that contains the methods you'll be using in your generic class StatisticItemHits, and use that interface as restriction. However I don't really see your requirements here, maybe you could post some more details about your scenario?
You could make StatisticItemHits<T>
an abstract class and create two subclasses:
StatisticItemHitsInt : StatisticItemHits<int>{}
StatisticItemHitsString : StatisticItemHits<string>{}
That way there can only be an int and string-representation of StatisticItemHits
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