Getting the SqlCommand Type from Generic T in .net

Go To StackoverFlow.com

0

i have created a generic function named ExecuteProcedure<T>(T command, string parameters), now inside the ExecuteProcedure function i want to cast the T into SqlCommand, so that i can use SqlCommand's properties like Parameters.Add() here is my code.

T could be SqlCommand or SqlDataAdapter

here's my code:

public void ExecuteProcedure<T>(T command, string parameters)
{
    using (connection)
    {
        if (typeof(T) == typeof(SqlCommand))
        {
           //how to convert into SqlCommand Here to use command.CommandType Property below.
        }
        command.CommandType = CommandType.StoredProcedure;
        foreach (string param in parameters.Split(','))
        {
            SqlParameter par = new SqlParameter(param, param.Substring(1, param.Length - 1));
            command.Parameters.Add(par);
        }


        connection.Open();
        command.ExecuteNonQuery();
    }
}
2012-04-03 23:23
by Abbas


0

You can use this code to CAST T to SqlCommand

SqlCommand cmd = (SqlCommand)Convert.ChangeType(command, typeof(SqlCommand));

anyways thanks @Chris

2012-04-03 23:56
by Abbas


0

I believe all you have to do is:

SqlCommand cmd = (SqlCommand)(object)command;
2012-04-03 23:28
by Chris Gessler
hi @Chris, i tried that, but its not working, it throws compile time error, saying cannot convert type T to System.Data.SqlClient.SqlComman - Abbas 2012-04-03 23:31
Ahh, yes, no constraint. Try casting to 'object' then to the known type. Answer updated - Chris Gessler 2012-04-03 23:39
Ads