I’m trying to refactor some code here that was done previously by other guys, since i find it quite unpractical
Here’s an example
protected void SetParameterValue(SqlParameter parameter, string parameterValue, bool isNullable)
{
if ((null == parameterValue || parameterValue == NULL_STRING) && isNullable)
parameter.Value = DBNull.Value;
else parameter.Value = parameterValue;
}
protected void SetParameterValue(SqlParameter parameter, int parameterValue, bool isNullable)
{
if (parameterValue == NULL_INT && isNullable)
parameter.Value = DBNull.Value;
else parameter.Value = parameterValue;
}
protected void SetParameterValue( SqlParameter parameter, Int64 parameterValue, bool isNullable)
{
if (parameterValue == NULL_LONG && isNullable)
parameter.Value = DBNull.Value;
else parameter.Value = parameterValue;
}
Like those, there are a lot more. Now i needed to create one that accepts a new type (which doesn’t have a method for it yet) and decided that maybe i could clean up a bit, make this better.
my idea is to create something like
protected void SetParameterValue<T>(SqlParameter parameter, T parameterValue, bool isNullable)
however, i don’t know what’s the best approach, what can i encapsulate inside this generic method and what will i need to do in separate methods as well. Is it worth it? or the “lots of methods” approach is fine? what would i gain from the generic one? thanks!
One way of removing the need for switches would be to use some kind of dictionary to hold delegates which determine what constitutes null for each possible type. Although I think you’d have to stick with object for this. So you’d have a dictionary and set it up like:
And your check would be like:
Although, as suggested by others, changing the code to use the Nullable type would be better.