I have the following method that currently works on int? variables. I’d like to extend it to any numeric nullable variables (e.g. decimal?, double?, etc…)
public static bool IsNullOrInvalid(this System.Nullable<int> source)
{
return (source == null || source == -1);
}
How can I pull this off?
The tricky bit is working out what “invalid” means in each case. If “any value which is deemed less than the default for the data type” is okay, you could try:
EDIT: As noted in comments, there’s no “numeric” constraint – it will be valid to call this method on every value type which is comparable with itself, such as
DateTime. There’s no way of avoiding that – adding more constraints would probably reduce the set slightly, but not completely.As for comparing with exactly -1, you’d need to be able to work out the value “-1” for every type. There’s no generic way of doing that. You could manually build a
Dictionary<Type, object>of “-1 for each type I’m interested in” but it would be pretty ugly.If -1 is invalid, is -2 really valid? That seems odd to me.