Ralph Ralph - 17 days ago 5
C# Question

TypeCast To Overcome Interface Limitation?

I'm using IDbCommand and IDbDataParameter interfaces for my SQL db logic but realized that I can't get

sqlCommand.parameter["ID"]
.Value because of an interface restriction.

Is it good practice to type cast an interfaced object to overcome a limitation of an interface?

Example

using (IDbCommand SqlCmd = CommandProvider.GetSPCommand(conn))
{
// setup sqlcmd with output paramter and executenonquery ...
ID = Convert.ToInt32(((SqlCommand)SqlCmd).Parameters["ID"].Value);
}

Answer

No, this is not good practice.

First, you shouldn't downcast unless absolutely necessary. If you need a value that is only provided by a interface implementation, start with that implementation. In your case, if CommandProvider.GetSPCommand returns a SqlCommand, then just do:

using (SqlCommand SqlCmd = CommandProvider.GetSPCommand(conn))
{
    // setup sqlcmd with output paramter and executenonquery ...
    ID = Convert.ToInt32(((SqlCommand)SqlCmd).Parameters["ID"].Value);
 }

If it doesn't do that, then you've run into the second thing you have wrong which is doing a cast before checking if it is safe. If the returned item wasn't a SqlCommand your code would throw an InvalidCastException. Instead, check with the as operator:

using (IDbCommand SqlCmd = CommandProvider.GetSPCommand(conn))
{
    SqlCommand fullSqlCommand = SqlCmd as SqlCommand;
    if (fullSqlCommand != null)
    {
       // setup sqlcmd with output paramter and executenonquery ...
       ID = Convert.ToInt32(fullSqlCommand.Parameters["ID"].Value);
    }
    else
    {
        //Some failsafe
    }
 }

Of course, only using the interface is the preferred option, but that can be difficult when, as in this case, you don't control it.

Comments