web analytics
How To Cast Object To Generic Datatype T? Options
codeling
Posted: Tuesday, May 30, 2017 1:21:06 PM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 892
Points: 3738

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."}

 

Sponsor
Posted: Tuesday, May 30, 2017 1:21:06 PM
 
codeling
Posted: Tuesday, May 30, 2017 1:23:31 PM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 892
Points: 3738

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));

}

Users browsing this topic
Guest

Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.


© 2017 Digcode.com. All rights reserved.