How can I represent, in a class, something that represents a Value.
This value will be used to write comparison operations on, like EqualTo, GreaterThan etc.
Now the catch is, the value could sometimes be an integer, string, or even a list of integers or strings.
How could I represent this in a class or groups of classes (maybe inheriting from a base class)
Could I then write a single method like:
EqualTo(IValue value, IValue otherValue)
How could this EqualTo method handle now if I passed in a string, or a list of strings, datetime or a list of datetimes and return true/false accordingly?
Note:
The catch is I will be building up these objects from data that comes from the database, so the actual dataType, value or values etc.
You could write:
or for greater than and less than:
Both of those would be pretty simple, given
IComparable<T>andIEquatable<T>🙂You’d need separate overloads (or different methods) to handle a sequence of such values though:
Alternatively, if you don’t want the generic constraint, you could use
Comparer<T>.DefaultandEqualityComparer<T>.Default.If you wanted to handle sequences in the same methods as non-sequences, you could always check whether
TimplementedIEquatable<T>and if not, whether it implementedIEnumerable<TElement>for someTElementwhich implementedIEquatable<TElement>. It would get pretty confusing, mind you…EDIT: Okay, if you’re going to be given these things dynamically…
First work out whether they’re lists or not. You’ll want to handle that separately. Assuming it really is
List<T>, you could do:Otherwise, use just the normal
Equals()call to check for equality, and cast a value to the non-genericIComparabletype for greater-than/less-than. It’s not ideal, but it should work…