Home > Blockchain >  Unable to cast object of type System.String to type System.Decimal
Unable to cast object of type System.String to type System.Decimal

Time:10-12

i am getting type conversion error what things i a doing wrong here ?

    private static T1 StringToDecimal<T1, T2>(T2 dummydata)
    {
        var type = typeof(T1);//string 
        var type2 = typeof(T2);//decimal
        Console.WriteLine("Type of T1 is : "   type);
        Console.WriteLine("Type of T2 is : "   type2);
        return (T1)Convert.ChangeType(dummydata, typeof(T2), CultureInfo.InvariantCulture);
        //System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.Decimal'.'

        //calling
        //string? _dummydata = "8468.45";
        //var getresult_ = StringToDecimal<string, decimal>(_dummydata);
    }

https://i.stack.imgur.com/KAOsO.png

Final working code

    private static TToConvertTo StringToDecimal<TToConvertFrom, TToConvertTo>(TToConvertFrom dummydata)
    {
        return (TToConvertTo)Convert.ChangeType(dummydata, typeof(TToConvertTo), CultureInfo.InvariantCulture);
    }

CodePudding user response:

You've simply mixed up your generic arguments. The conversion is working, but the subsequent cast is failing.

Consider the following correct implementation with updated generic type names that make sit more obvious what is happening:

private static TToConvertTo StringToDecimal<TToConvertFrom, TToConvertTo>(
    TToConvertFrom dummydata)
{
    var type = typeof(TToConvertFrom);//string 
    var type2 = typeof(TToConvertTo);//decimal
    Console.WriteLine("Type of T1 is : "   type);
    Console.WriteLine("Type of T2 is : "   type2);

    return (TToConvertTo)Convert.ChangeType(dummydata, type2,
        CultureInfo.InvariantCulture);
}
  • Related