Home > Software engineering >  converting ValueType to BigInteger threw exception: System.InvalidCastException: Specified cast is n
converting ValueType to BigInteger threw exception: System.InvalidCastException: Specified cast is n

Time:07-14

Following the MSDN example of ValueType Class on this lines

  // Use BigInteger as common integral type
  if (IsInteger(value1) && IsInteger(value2)) {

     BigInteger bigint1 = (BigInteger) value1; // threw exception: System.InvalidCastException
     BigInteger bigint2 = (BigInteger) value2; // threw exception: System.InvalidCastException

     return (NumericRelationship) BigInteger.Compare(bigint1, bigint2);
  }

the cast to BigInteger throws System.InvalidCastException Specified cast is not valid.

If I add on the example, a line that make the code pass from there, I got the exception.

public class Example
{
   public static void Main()
   {
        Console.WriteLine("{0} {1} {2}", 19, Utility.Compare(19, 19), 19);
   }
}

On IL code I see that its just make unboxing, as the ValueType is an object... and not convert the number to BigInteger.

So is this a bug, is this something that I don't understand?

How to convert a ValueType to BigInteger ?

Of course one way is this:

public static BigInteger ConvertToBigInteger(ValueType value)
{
    if (value is Int32)
        return new BigInteger((Int32)value);

    if (value is Int16)
        return new BigInteger((Int16)value);

    if (value is Int64)
        return new BigInteger((Int64)value);

    if (value is Byte)
        return new BigInteger((Byte)value);

    if (value is UInt32)
        return new BigInteger((UInt32)value);

    if (value is UInt16)
        return new BigInteger((UInt16)value);

    if (value is UInt64)
        return new BigInteger((UInt64)value);

    if (value is SByte)
        return new BigInteger((SByte)value);

    return (BigInteger)value;
}

on dotnetfiddle.net

The code from MSDN to dotnetfiddle.net with the extra line that make it pass from the part that's throw the exception https://dotnetfiddle.net/oyaVvm

The same code with the convert I mention https://dotnetfiddle.net/kN7iNA is working

CodePudding user response:

// Just an example that caters for Int64
public static BigInteger toBigInt(ValueType value)
{   
    BigInteger response = Convert.ToInt64(value);
    return response;
}

Update: I updated your dotnet fiddle to cater for your unsigned value with a catch all to work off of the string constructor.

https://dotnetfiddle.net/jNHBo2

public static BigInteger toBigInt(ValueType value)
{   
    BigInteger response;
    if(value is Int64)
        response = Convert.ToInt64(value);
    else if (value is UInt64)
        response = Convert.ToUInt64(value);
    else 
        response = BigInteger.Parse(value.ToString());
    return response;
} 

CodePudding user response:

Give this a try.

BigInteger bigint1 = new BigInteger((int)value1);
BigInteger bigint2 = new BigInteger((int)value2);

  • Related