rohit89
rohit89

Reputation: 5773

Limiting generic types in C#

I have a generic class MyClass<T> where T should only be those types which can be compared.

This would mean only numeric types and classes where methods for the relational operators have been defined. How do I do this ?

Upvotes: 9

Views: 5991

Answers (4)

Anthony Pegram
Anthony Pegram

Reputation: 126854

You cannot constrain to operators, but you can constrain to interfaces. Therefore, intending to use >=, <=, == is out, but you could use CompareTo, Equals.

where T : IComparable<T>

Interface documentation

This interface brings you the CompareTo method which is useful for relational ordering (greater than, less than, etc.). Primitives and strings implement this already, but you would need to implement this for your own custom types. You would use it like this

void SomeMethod<T>(T alpha, T beta) where T : IComparable<T>
{
    if (alpha.CompareTo(beta) > 0) 
    {
        // alpha is greater than beta, replaces alpha > beta
    }
    else if (alpha.CompareTo(beta) < 0)
    {
        // alpha is less than beta, replaces alpha < beta
    }
    else 
    {
        // CompareTo returns 0, alpha equals beta
    }
}

Equals you get by default as a virtual method on object. You want to override this method on your own custom types if you want something other than referential equality to be used. (It is also strongly recommended to override GetHashCode at the same time.)

Upvotes: 11

msedi
msedi

Reputation: 1733

If speed is of relevance using the suggested methods will give you a tremendous loss in performance. If not, all the suggested things work fine.

This is an issue I have to address very often since the primitive datatypes in C# do not have an "Numeric" datatype as often suggested and demanded by others here.

Maybe the next release of C# will have it, but I doubt...

Upvotes: -1

JaCraig
JaCraig

Reputation: 1078

If you want to limit it to things that can be compared, you can do things like:

public class MyClass<T> where T:IComparable

Upvotes: 3

user26901
user26901

Reputation:

You can limit the generic type to only classes that implement the IComparable interface using the where modifier.

public class MyClass<K> where K : IComparable
{
  ....
}

Upvotes: 3

Related Questions