patterncsharpMinor
Optimize parsing more and more
Viewed 0 times
andmoreparsingoptimize
Problem
I have the below C# code for parsing. Do you think this is most optimized or should I use a generic method in these functions themselves?
public static bool GetDBBool(object value)
{
var result = false;
if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
bool.TryParse(value.ToString(), out result);
return result;
}
public static int GetDBInt(object value)
{
var result = -999;
if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
int.TryParse(value.ToString(), out result);
return result;
}
public static double GetDBDouble(object value)
{
var result = -999.00;
if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
double.TryParse(value.ToString(), out result);
return result;
}
public static DateTime GetDBDate(object value)
{
var result = DateTime.Now;
if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
DateTime.TryParse(value.ToString(), out result);
return result;
}
public static DateTime? GetDBNullableDate(object value)
{
DateTime date;
if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
return DateTime.TryParse(value.ToString(), out date) ? date : (DateTime?)null;
else
return null;
}Solution
== false is not very readable. Use ! instead. If the "object value" is already of desired type (e.g. DateTime), it would be slower to convert it to string and then back again.
I would write instead
if (value is DateTime) return (DateTime)value;I would not use var result = -999; as a return value.
If the conversion fails, you can either return Int32.MinValue (better than -999) or rather null.
Maybe also you would like to check for DBNull.Value?
So first I would check for null and DBNull.Value, then "value is DateTime" check and the last thing would be DateTime.TryParse.
Code Snippets
if (value is DateTime) return (DateTime)value;Context
StackExchange Code Review Q#56833, answer score: 6
Revisions (0)
No revisions yet.