BigInteger Narrowing Conversion (BigInteger to Int32)

 

Defines an explicit conversion of a BigInteger object to a 32-bit signed integer value.

Namespace:   System.Numerics
Assembly:  System.Numerics (in System.Numerics.dll)

Public Shared Narrowing Operator CType (
	value As BigInteger
) As Integer

Parameters

value
Type: System.Numerics.BigInteger

The value to convert to a 32-bit signed integer.

Return Value

Type: System.Int32

An object that contains the value of the value parameter.

Exception Condition
OverflowException

value is less than Int32.MinValue.

-or-

value is greater than Int32.MaxValue.

The overloads of the Narrowing(Decimal to BigInteger) method define the types to which or from which a BigInteger object can be converted. Language compilers do not perform this conversion automatically because it can involve data loss. Instead, they perform the conversion only if a casting operator (in C#) or a conversion function (such as CType or CInt in Visual Basic) is used. Otherwise, they display a compiler error.

Because this operation defines a narrowing conversion, it can throw an OverflowException at run time if the BigInteger value is outside the range of the Int32 data type. There is no loss of precision in the resulting Int32 value if the conversion is successful.

The following example illustrates the conversion of BigInteger values to Int32 values. It also handles an OverflowException that is thrown because the BigInteger value is outside the range of the Int32 data type.

' BigInteger to Int32 conversion.
Dim goodInteger As BigInteger = 200000
Dim badInteger As BigInteger = 65000000000

Dim integerFromBigInteger As Integer

' Convert using CType function.
integerFromBigInteger = CType(goodInteger, Integer)
Console.WriteLine(integerFromBigInteger)
' Convert using CInt function.
integerFromBigInteger = CInt(goodInteger)
Console.WriteLIne(integerFromBigInteger)

' Handle conversion that should result in overflow.
Try
   integerFromBigInteger = CType(badInteger, Integer)
   Console.WriteLine(integerFromBigInteger)
Catch e As OverflowException
   Console.WriteLine("Unable to convert {0}:{1}   {2}", _
                     badInteger, vbCrLf, e.Message)
End Try
Console.WriteLine()

Universal Windows Platform
Available since 8
.NET Framework
Available since 4.0
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 4.0
Windows Phone
Available since 8.1
Return to top
Show: