I have a class which has a property of generic type as given below. Type T can be any number (short, int, float …)
public class EqualFilter <T> : Filter {
private T _value;
public override T Value {
get {
return _value;
}
set {
if (!EqualityComparer<T>.Default.Equals(_value, value)) {
_value = value;
RaiseFilteringChanged();
}
}
}
.....
}
Now I have a client class which has a “String” that needs to be passed to the above setter. Now at the time of setting the value in the above setter, the type T is already determined at runtime and I can get hold of that type as Type T in my client. Is it possible to convert the string to the appropriate type ,as identified by the EqualFilter, in client program? Something like this that is not working
Type T = filter.getFilterType();
filter.Value = (T) myTextBox.Text;
The below code works but it will involve if-else for all the types that can be numeric.
Type T = filter.getFilterType();
if (T == typeof(int)) {
filter.Value = Int32.Parse(myTextBox.Text);
} else if() {
....
}
In short I am not sure how to approach the issue in a better way.
It sounds like you’re doing something similar to data binding. If all you’re interested in is working with strings, you might consider constraining the generic type to
IConvertibleand calling theConvert.ChangeTypemethod from a special setter method like so:The generic type constraint permits only those types that Convert.ChangeType can operate upon. Besides the integral and floating point types, this also permits use of the types
string,decimalandDateTime. Just be aware thatstringtypes may not always be exact when working with thedoubletype as there can be round-off and floating point representation errors. Also there may be other exceptions that you may want to catch to make this more robust (FormatExceptionandOverflowException, for instance).The big switch statement, in this case, is handled by the framework in the
ChangeTypemethod.Edit:
Adding the
Console.WriteLineoutput from my version of the code above (that has overrides and base-class usage commented-out):