I've got the task convert variable of nullable type to not nullable if it's nullable and redefine default values for types, if it's required. I wrote generic static class for it, but, unfortunately, it works to slow. This class will be used in reading data from database to model, so performance is very important. Here is my class.
public static class NullableTypesValueGetter<T> where T : struct
{
#region [Default types values]
private static DateTime currentDefaultDateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
#endregion
#region [Default types to string values]
private const string nullableDateTimeValue = "DateTime?";
#endregion
public static T GetValue(dynamic value)
{
if (Nullable.GetUnderlyingType(value.GetType()) != null) //if variable is nullable
{
var nullableValue = value as T?;
//if variable has value
if (nullableValue.HasValue)
{
return nullableValue.Value;
}
//if hasn't
else
{
var result = default(T);
//extensionable code, determination default values
var @switch = new Dictionary<Type, string>
{
{typeof(DateTime?), nullableDateTimeValue}
};
//redefining result, if required
if (@switch.Any(d => d.Key.Equals(nullableValue.GetType())))
{
switch (@switch[nullableValue.GetType()])
{
//extensionable code
case (nullableDateTimeValue):
{
result = GetDefaultDateTimeValue();
} break;
}
}
return result;
}
}
//if not nullable
else
{
return value;
}
}
private static T GetDefaultDateTimeValue()
{
return (T)Convert.ChangeType(new DateTime?(currentDefaultDateTime), typeof(T));
}
}
Do you know any others realizations of this class or any ways to improve performance of this?