Converting Variables

Knowing how to convert variables from one data type to another is important for programmers. C# offers many ways to perform these conversions. Sometimes, as in the Simple Math program, the conversion is done automatically. Other times, you have to do the conversion explicitly. Fortunately, C# makes variable conversion easy. As usual, it makes sense to look at a working program (see Figure 2.4):

Figure 2.4. Although the console works only with string values, you can convert strings to whatever type of variable you wish.


using System;

namespace ConvertDemo
{

   ///<summary>
   /// demonstrates various types of variable conversions
   /// Andy Harris, 11/09/01
   ///</summary>

   class ConvertDemo
   {
     static void Main()
     {
       int myInt;
       double myDouble;
       string myString;

       myInt = 5;

       //copying an int to a double causes no problems
       myDouble = myInt;
       Console.WriteLine("myDouble is {0}.", myDouble);

       //copying a double to an int won't work!
       myDouble = 3.5;
       //myInt = myDouble;    //this line causes an error
       //Console.WriteLine(myInt); 
      //You can explicitly cast, but you might lose data
      myInt = (int)myDouble;
      Console.WriteLine("After casting, myInt = {0}.", myInt);

      myString = myDouble.ToString();
      Console.WriteLine("myDouble as a String: {0}", myString);

      Console.Write("Please enter a number: ");
      myString = Console.ReadLine();

      Console.WriteLine("myString converted to double: {0}",
Convert.ToDouble(myString));
    } // end main
  } // end class
} // end namespace

Some programmers prefer some alternate syntaxes, such as myFloat.Parse(someString) or myInt.Parse(someString). However, the Convert syntax works on all variables types, so it’s a pretty convenient solution.

To illustrate some key conversion ideas, I created an int, a double, and a string. These are, by far, the most common variable types you will use. I started by assigning the value 5 (an integer value) to myInt. Then, I copied the value of myInt to the myDouble variable. This caused no problems because a double can easily hold all the information in an int. However, the next few lines of code assign the value 3.5 to myDouble and then try to copy the value of myDouble to myInt. In the preceding source code, I’ve placed the comment characters before this line so it will not execute. This is commonly called commenting out code.

I commented out that particular line of code because it causes the system to crash. You cannot copy a double value to an int because doubles have more information (namely, the information after the decimal point). You can’t even copy the value 3.0 to an int variable directly because 3.0 is a double value.

Explicit Casting

You can convert a double value to an integer value, but you will lose some information along the way. Take a look at this line:

myInt = (int)myDouble;

This line copies the value of myDouble to myInt successfully, but it does so by utilizing a trick called casting, in which the term (int) tells the compiler to convert the value immediately following into an integer value. This results in a loss of data, but it works. You can use this type of operation to convert any numeric data types.

The Convert Object

Strings are not like other types of data because the amount of information necessary to store a string can vary, based on the length of the string. You don’t have to worry about this, but you should know that the conversion techniques that work between numbers do not work the same way with string variables. The string value "123" is not the same as the int value 123 or the double value 123.0. You cannot use a casting operation to convert to or from a string value. Therefore,

myInt = (int)"123"

does not work, and

myString = (string) 123

does not work, either.

NOTE

IN THE REAL WORLD

Converting numeric data to strings is important because all the user generally sees is text information. When the user types something, the program usually sees it as a string value. For example, the Console.ReadLine() method always results in a string value. If you want to get a number from the user, you have to take the string from the ReadLine() method and convert it to a number yourself.

Fortunately, C# has an object that specializes in converting variables between types, and it always works. The convert object, pictured in Figure 2.5, is a special object that provides several useful methods. Methods are actions an object can perform. Most of the convert object’s methods convert data from one type to another.

Figure 2.5. The convert object can convert nearly any variable type to any other variable type.


The Convert class is part of the System namespace, so you already have access to it. To use the class, you call one of its methods. For example,

myInt = Convert.ToInt32("123");

converts the string value "123" into an integer and stores that value into myInt. Likewise, the statement

myString = Convert.ToString(123);

takes the int value 123 and converts it into a string for storage in the myString variable. Of course, you usually won’t use the Convert class with literal values, as I’ve done in these examples. Generally, you stuff a variable in the ToInt32() or ToString() method, like this:

myInt = Convert.ToInt32(myString);

Because you sometimes grab a numeric value from the console, you often simply put the Console.ReadLine() method inside the ToInt() parentheses, like this:

myInt = Convert.ToInt32(Console.ReadLine());

The convert object isn’t foolproof. If you let the user type in data, you don’t have any way to know whether he or she added a decimal point. You might be tempted to write code like this:

myInt = Convert.ToInt32(Console.ReadLine());

This code works great if the user types an integer, but if the user enters a real number with a decimal point, your program will crash. It is safer to do the same operation in two steps, like this:

myDouble = Convert.ToDouble(Console.ReadLine()); myInt = (int) myDouble;

The compiler will have no problem converting a decimal value into a double, and then you can explicitly cast the double to an int.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.8.8