I have a method taking an object and returning it in string format with some stuff depending on the type. For example:
ConvertObjectToSQL(1); // "1"
ConvertObjectToSQL("Foo"); // "'Foo'"
ConvertObjectToSQL(DateTime.Now); // "'2017/02/22 00:00:00'"
My problem occurs when I provide an enum to that method. I want my method to act as if I provided it the enum underlying type. Of course, my method is called in a context where I can't possibly know the enum type.
In the first place, here is what I did:
private string ConvertObjectToSQL(object obj)
{
if (obj == null)
{
return "NULL";
}
else if (obj is DateTime)
{
return "'" + obj.ToString() + "'";
}
else if (obj is string)
{
return "'" + obj.ToString().Replace("'", "''") + "'";
}
return obj.ToString();
}
But if my enum is:
enum FooEnum : int { Foo = 0, Bar = 1 }
If want :
ConvertObjectToSQL(FooEnum.Foo); // "0"
ConvertObjectToSQL(FooEnum.Bar); // "1"
But it actually returns:
ConvertObjectToSQL(FooEnum.Foo); // "Foo"
ConvertObjectToSQL(FooEnum.Bar); // "Bar"
So I end up with a new else if doing the job:
else if (obj is Enum)
{
var baseType = Enum.GetUnderlyingType(obj.GetType());
return Convert.ChangeType(obj, baseType).ToString();
}
My question is: can I avoid reflexion here? Because this methods is called a lots of times.
ConvertObjectToSQL(((int)FooEnum.Foo).toString())int...my method is called in a context where I can't possibly know the enum type. So as said @Chris, the enum is not necessarily based on int.