Reputation: 679
I have a class that contains a two sets of data.
Now, X and Y could hold either a string/double/integer/datetime in any possible combination. The only rule being that at any given point of time, both lists must contain equal number of values.
I could solve the problem of always holding equal data by providing access only through an AddXY method and a RemoveAt method (ensuring that at any given point of time, I can guarantee that both the X List and Y List are equally sized).
Further, I'd like the end user of this class to be able to access the X and Y values through indexers as shown below.
someClassInstance.X[i] and someClassInstance.Y[i]
Since, there are no options for this in C#, I have opted for exposing X and Y as IList (AsReadOnly) method.
Now, I considered the idea of constraining the types by using Generics. But I am unable to find appropriate examples for this particular case.
How do I say
public class MyClass<P, Q>
where P : Double, String, Integer, DateTime
and Q : Double, String, Integer, DateTime
Should I discard the idea altogether and look at some kind of Tuple or some such data structure?
EDIT: I also know that the constraints cannot be Value Types, so how does this work?
Upvotes: 1
Views: 864
Reputation: 26782
What you are asking is not possible in C#. There is no generic type constraint that unifies these types.
The best you can do is check at runtime, for example in the static constructor. Something like this:
public class MyClass<P, Q>
{
static MyClass()
{
if (IsValidType(typeof(P)
&& IsValidType(typeof(Q))
throw new NotSupportedException("invalid type for MyDataStructure");
}
static bool IsValidType(Type type)
{
// logic to check whether type is acceptable
return true;
}
}
However I'd advise against this since it seems somewhat artificial.
Upvotes: 4