web analytics

How To Cast Object To Generic Datatype T?

Options

codeling 1602 - 6666
@2017-05-30 13:21:06

The following C# method will throw exception " when converting an object to decimal data type:

public static T ComputeVariableValue<T>(string stmt)

{

    DatabaseManager dbMgr = ConfigurationBasedFactory.Current.GetInstance<DatabaseManager>("DataStore");

    DatabaseResult set = dbMgr.Execute( DatabaseExecutionType.Scalar, CommandType.Text, stmt);

    return (T)set.ResultScalar;

}

[System.InvalidCastException] = {"Specified cast is not valid."}

 

@2017-05-30 13:23:31

Try Convert.ChangeType() method as below:

public static T ComputeVariableValue<T>(string stmt)

{

    DatabaseManager dbMgr = ConfigurationBasedFactory.Current.GetInstance<DatabaseManager>("DataStore");

    DatabaseResult set = dbMgr.Execute( DatabaseExecutionType.Scalar, CommandType.Text, stmt);

    return (T)Convert.ChangeType(set.ResultScalar, typeof(T));

}

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com