Home

Mathematics in C#: Value Conversions

 

Implicit Conversions

In Lesson 1, we saw how to declare variables of integral, floating-point, and string types. We also saw how to initialize the variables. If you have a program with mixed types of variables, you may be interested in converting the value of one into another. Again, in Lesson 1, we saw how much memory space the variable of each data type required in order to hold its value. Here is a summary of what we learned:

Data Type Name Memory Size
byte Byte 8 bits
sbyte Signed Byte 8 bits
char Character 16 bits
short Small Integer 16 bits
ushort Unsigned Small Integer 16 bits
int Signed Integer 32 bits
uint Unsigned Integer 32 bits
float Single-Precision Floating-Point Number 32 bits
double Double-Precision Floating-Point Number 64 bits
long Signed Long Integer 64 bits
ulong Unsigned Long Integer 64 bits
decimal Extended Precision Floating-Point Number 128 bits

As you can see, a value held by a Byte variable can fit in the memory reserved for an int variable, which can be carried by a long variable. Thanks to this, you can assign a Byte value to an int variable, or an int variable to a long variable. Also, based on this, because the memory reserved for an int variable is larger than the one reserved for a double variable, you can assign a variable of the former to a variable of the latter. Here is an example:

using System;

class Program
{
    static int Main()
    {
        int iNumber = 2445;
        double dNumber = iNumber;

        Console.WriteLine("Number = {0}", iNumber);
        Console.WriteLine("Number = {0}\n", dNumber);
        return 0;
    }
} 

This would produce:

Number = 2445
Number = 2445

Press any key to continue . . .

This characteristic is referred to as implicit conversion.

Explicit Conversions

Because of memory requirements, the direct reverse of implicit conversion is not possible. Since the memory reserved for a short variable is smaller than that of an int, you cannot assign the value of an int to a short variable. Consider the following program:

using System;

class Program
{
    static int Main()
    {
        int iNumber   = 168;
        short sNumber = iNumber;

        Console.WriteLine("Number = {0}", iNumber);
        Console.WriteLine("Number = {0}\n", sNumber);
        return 0;
    }
}

This would produce the following error:

Cannot implicitly convert type 'int' to 'short'.

Value casting consists of converting a value of one type into a value of another type. For example, you may have an integer value and you may want that value in an expression that expects a short. Value casing is also referred to as explicit conversion.

To cast a value or a variable, precede it with the desired data type in parentheses. Here is an example:

using System;

class Program
{
    static int Main()
    {
        int iNumber   = 168;
        short sNumber = (short)iNumber;

        Console.WriteLine("Number = {0}", iNumber);
        Console.WriteLine("Number = {0}\n", sNumber);
        return 0;
    }
}

This would produce:

Number = 168
Number = 168

Press any key to continue . . .

When performing explicit conversion, you should pay close attention to the value that is being cast. If you want an integer value to be assigned to a short variable, the value must fit in 16 bits, which means it must be between -32768 and 32767. Any value beyond this range would proceed an unpredictable result. Consider the following program:

using System;

class Program
{
    static int Main()
    {
        int iNumber   = 680044;
        short sNumber = (short)iNumber;

        Console.WriteLine("Number = {0}", iNumber);
        Console.WriteLine("Number = {0}\n", sNumber);
        return 0;
    }
}

This would produce:

Number = 680044
Number = 24684

Press any key to continue . . .

Notice that the result is not reasonable.

The Convert Class

Each C# data type, which is adapted from a .NET Framework structure, is equipped with a ToString() method that could be used to convert its value to a String type. We didn't address the possibility of converting a value from one primitive type to another. To support the conversion of a value from one type to another, the .NET Framework provides a class named Convert. This class is equipped with various static methods; they are so numerous that we cannot review all of them.

Remember that each primitive data type of the C# language is type-defined from a .NET Framework structure as follows:

C# Data Type Name .NET Framework Structure
bool Bollean Boolean
byte Byte Byte
sbyte Signed Byte SByte
char Character Char
short Small Integer Int16
ushort Unsigned Small Integer UInt16
int Integer Int32
uint Unsigned Integer UInt32
long Long Integer Int64
ulong Unsigned Long Integer UInt64
float Single-Precision Floating-Point Single
double Double-Precision Floating-Point Double
decimal Extended Precision Floating-Point Number Decimal
No Explicit Type Date/Time Value DateTime
string String String

To adapt the Convert class to each C# data type, the class is equipped with a static method whose name starts with To, ends with the .NET Framework name of its structure, and takes as argument the type that needs to be converted. Based on this, to convert a decimal number of a double type to a number of int type, you can call the ToInt32() method and pass the double variable as argument. Its syntax is:

public static int ToInt32(double value);

Here is an example:

using System;

class Program
{
    static int Main()
    {
        double dNumber = 34987.68D;
        int iNumber = Convert.ToInt32(dNumber);

        Console.WriteLine("Number: {0}", dNumber);
        Console.WriteLine("Number: {0}", iNumber);
        return 0;
    }
}

 

 

Previous Copyright © 2006-2016, FunctionX, Inc. Next