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 ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You cannot constrain to operators, but you can constrain to interfaces. Therefore, intending to use
>=, <=, ==is out, but you could useCompareTo, Equals.Interface documentation
This interface brings you the
CompareTomethod 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 thisEqualsyou get by default as a virtual method onobject. 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 overrideGetHashCodeat the same time.)