CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
Note The System.Numerics namespace defines a second structure named Complex, which allows you to
model mathematically complex numerical data (e.g., imaginary units, real data, hyperbolic tangents). Consult the
.NET Framework 4.5 SDK documentation if you are interested.
While many of your .NET applications might never need to make use of the BigInteger structure, if
you do find the need to define a massive numerical value, your first step is to reference the
System.Numerics.dll assembly into your project. If you wish to follow along with the current example,
perform the following tasks:
1.
Select the Project Add Reference… menu option of Visual Studio.
2.
Locate and select the System.Numerics.dll assembly within the list of
presented libraries.
3.
Press the Add button, then the Close button.
After you have done so, add the following using directive to the file, which will be using the
BigInteger data type:
// BigInteger lives here!
using System.Numerics;
At this point, you can create a BigInteger variable using the new operator. Within the constructor,
you can specify a numerical value, including floating-point data. However, recall that when you define a
literal whole number (such as 500), the runtime will default the data type to an int. Likewise, literal
floating-point data (such as 55.333) will default to a double. How, then, can you set BigInteger to a
massive value while not overflowing the default data types used for raw numerical values?
The simplest approach is to establish the massive numerical value as a text literal, which can be
converted into a BigInteger variable via the static Parse() method. If required, you can also pass in a
byte array directly to the constructor of the BigInteger class.
Note After you assign a value to a BigInteger variable, you cannot change it, as the data is immutable.
However, the BigInteger class defines a number of members that will return new BigInteger objects based on
your data modifications (such as the static Multiply() method used in the proceeding code sample).
In any case, after you have defined a BigInteger variable, you will find this class defines very similar
members as other intrinsic C# data types (e.g., float, int). In addition, the BigInteger class defines
several static members that allow you to apply basic mathematical expressions (such as adding and
multiplying) to BigInteger variables. Here is an example of working with the BigInteger class.
static void UseBigInteger()
{
Console.WriteLine("=> Use BigInteger:");
BigInteger biggy =
BigInteger.Parse("9999999999999999999999999999999999999999999999");
94