vba_user
vba_user

Reputation: 125

Cannot implicitly convert type 'System.Numerics.BigInteger' to 'int'. An explicit conversion exists (are you missing a cast?)

I have an array and simple loop:

static BigInteger[] dataSet = new BigInteger[] { 100913, 1009139, 10091401, 100914061, 1009140611, 10091406133, 100914061337, 1009140613399 };


 foreach (BigInteger num in dataSet ) {

                BigInteger[] Vector = new BigInteger[num];

                for (BigInteger i = 1; i <= num; i++)  {
                    Vector[i - 1] = i;
                }
            }

Can anyone explain why this code returns

Cannot implicitly convert type 'System.Numerics.BigInteger' to 'int'. An explicit conversion exists (are you missing a cast?)

Error appears in this line:

BigInteger[] Vector = new BigInteger[num]; 

Everything is converted to BigInteger, I do not see the possible reasons.

Will be thankful for help,

Thanks in advance,

Upvotes: 3

Views: 1667

Answers (2)

Igor Yalovoy
Igor Yalovoy

Reputation: 1725

I would suggest to drop idea of using BigInteger in the way you use, because you would run out of memory allocating array with value higher than int.MaxValue. Arrays and List are limited to int.MaxValue for a purpose. Integer would cover your needs in case of array usage in 99.9% cases.

I wonder what are you trying to archive, why do you need such huge arrays filed with just incrementing counter?

In order to make your code compile you need to cast your BigIntegers:

         foreach (BigInteger num in dataSet ) {

            BigInteger[] Vector = new BigInteger[(int)num];

            for (BigInteger i = 1; i <= num; i++)  {
                Vector[(int)(i - 1)] = i;
            }
        }

But your code most likely fail due to either out of memory or out of range exception, because BigInteger > Integer.

Upvotes: 0

DavidG
DavidG

Reputation: 119076

num is a BigInteger but you are using it to initialise the size of your array:

BigInteger[] Vector = new BigInteger[num];

The indexer of an array is int, meaning that largest size you can create is int.MaxValue (2,147,483,647).

Upvotes: 8

Related Questions