I’m not quite sure how to resolve this and my current implementation is clunky. I have a generic method in my class that applies a numeric value to a combo box’s Value property. I would like this method to work for ints, floats, decimals, and doubles. Internally it will cast to a decimal. Here is my code currently:
private void UpdateValueFromComboBox<T>(ComboBox tSource, NumericUpDown tDest)
{
NamedKeyValuePair<String, T> tKV = tSource.SelectedItem as NamedKeyValuePair<String, T>;
if (tKV != null)
{
// Update the Control's value with what was saved
tDest.Value = Decimal.Parse(tKV.Value.ToString());
}
}
What I want to do is get rid of the ToString() and Parse() calls. Basically, I want the assignment to be as follows:
tDest.Value = (Decimal) tKV.Value;
But because C# doesn’t know what ‘T’ is or will be, it gives me an error. I get an error that “Cannot convert type ‘T’ to ‘decimal'”. Is there a way to specify, using the Where keyword, that the values being passed in are numeric??
This is not possible.
Instead, you can add
where T : struct, IConvertibleand calltKV.Value.ToDecimal(CultureInfo.InvariantCulture).