1

I have a SQL query builder method:

public static string PreprocessSQL(string sql, params object[] args) 

Provided that the sql parameter is "String.Format friendly", this method loops through the params and plugs them into the query string, doing whatever needs to be done based on the type of the argument - convert a null to string "NULL", surround a string with single quotes, etc.

Now the problem is with enums. I need a logic that checks if the type of current args[i] is Enum, and if so, convert it to int. How to do this check? My first guess, for some reason, doesn't work:

if(args[i].GetType() == typeof(Enum)) {
    converted.Add((int)args[i]);
}

The above condition apparently gets evaluated as false.

My enum class is:

public enum Priority {
    Low,
    Normal,
    High
}

If a pass a value of Priorty.Normal to this method, I figured the "value" is Normal, and the type of that value is Priority, which autmatically inherits from Enum, so I'm done. Turns out it's not that simple, and from what I can tell, it looks like the type of the value Normal is actually Priority.Normal

Now I could explicitly check for all the enums I'm using in my project, it's only 2 classes actually, but would that even work?

if(args[i].GetType() == typeof(Priority)) { ... }

I mean, if type of args[i] is Priority.Normal, this would too evaluate as false.

How do I check an unknown object o has the type of a enumeration class?

oli.G
  • 1,300
  • 2
  • 18
  • 24
  • possible duplicate of [Getting Type of Enum witnin class through C# reflection](http://stackoverflow.com/questions/9408800/getting-type-of-enum-witnin-class-through-c-sharp-reflection) – SQLMason Nov 19 '13 at 12:14
  • 1
    http://social.msdn.microsoft.com/Forums/vstudio/en-US/a78445ca-c004-4612-938b-0a70734f817e/enum-gettype?forum=csharpgeneral – SQLMason Nov 19 '13 at 12:16

3 Answers3

3

You can check IsEnum property.

args[i].GetType().IsEnum

Or

if(args[i] is Enum)
{
}

Or

bool isEnum = typeof(Enum).IsAssignableFrom(args[i].GetType());

Or

bool isEnum = typeof(Enum).IsInstanceOfType(o);
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
1

Try this

 bool isEnum = o is Enum;
Microsoft DN
  • 9,706
  • 10
  • 51
  • 71
0

You can leverage the IsEnum property of System.Type

bool isEnum = typeof(YourType).IsEnum
Moo-Juice
  • 38,257
  • 10
  • 78
  • 128