I am using parameterized query in C# with following piece of code:
int i = 5;
string query = "select col1 from table where col2 = @prm1 and col3 = @prm2";
SqlCommand cmd = new SqlCommand(query,connection);
cmd.Parameters.Add(new SqlParameter("@prm1", (int)MyEnum.val1));
cmd.Parameters.Add(new SqlParameter("@prm2", i);
public enum MyEnum
{
val1 = 0,
val2 = 100,
val3 = 150
}
Now, the built-in class SqlParameter
has 2 overloaded method with 2 params as follows :
public SqlParameter(string parameterName, SqlDbType dbType);
public SqlParameter(string parameterName, object value);
Now, for @prm2
, where I am passing int
variable, it's correctly initializing parameter with proper value. But for @prm1
, where I am passing enum & converting it as int
as value, it's taking it as 1st method of SqlParameter
.
Built-in SqlDbType
enum is as follows:
public enum SqlDbType
{
BigInt = 0,
Binary = 1,
....
....
}
Since the value of enum I am passing is 0
, it is taking that 0 and using first method and creating a parameter with BigInt
DATATYPE instead of creating param with value 0
.
What could be the reason behind this? Is it some sort of bug or am I missing some silly point here?
Update: Although this provides answer to my original question, which says '0 is implicitly convertable to enum, but non-zero value isn't' hence the difference in choosing method for both statements. I've tried following:
cmd.Parameters.Add(new SqlParameter("@prm1", (int)MyEnum.val1));
cmd.Parameters.Add(new SqlParameter("@prm1", Convert.ToInt32(MyEnum.val1)));
1st statement calling method with SqlDbType
arg & 2nd is calling method with object
value, even though I'm basically passing both values as int
. Any explaination for that?