Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting T to string and int?

Tags:

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?

like image 407
Mats Avatar asked Jan 18 '09 12:01

Mats


People also ask

Which keyword is used to apply constraints on type parameter?

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.

How do you restrict a generic class?

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.

Is Int a generic type?

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.


2 Answers

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?

like image 117
driAn Avatar answered Oct 20 '22 05:10

driAn


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

like image 38
Ruben Avatar answered Oct 20 '22 07:10

Ruben