Convert A Variable

You will want to convert variables when performing operations that require all variables to be the same data type. For example, suppose you want to add numbers together, and the numbers are held in string variables. Some languages, like Visual Basic 6, will do an implicit conversion, but not in the case of C#. Another example of where you may want to convert is using a method on a class. For example, the Response.Write method expects a string data type to be passed for the first parameter. If another data type is passed, a runtime error will occur.

Many functions are available to convert from one data type to another data type. So, the first thing to do when converting from one data type to another data type is to look up the appropriate function for the conversion. An example of a function that you will use often is the function that converts to a string. To use this method, you simply use the ToString() method call at the end of the variable.

There are two different types of conversions: an implicit conversion and an explicit conversion. An implicit conversion is done when you cast another variable into a variable of a different data type. Be careful when you do this, because sometimes the variable you are casting into cannot hold the original variable.

CONVERT A VARIABLE

CONVERT A VARIABLE

D Open your text editor.

^0 Type using System; to import the System namespace and press Enter.

< Type the name of the class you want to create and press Enter.

S Between the curly braces, create the Main function.

—0 Declare a byte variable and initialize the value to 3.

Q Declare an integer variable and initialize the value to the byte variable created.

D Open your text editor.

^0 Type using System; to import the System namespace and press Enter.

< Type the name of the class you want to create and press Enter.

^Q Type { }, placing the opening and closing curly braces on separate lines, to set off the body of the class.

S Between the curly braces, create the Main function.

—0 Declare a byte variable and initialize the value to 3.

Q Declare an integer variable and initialize the value to the byte variable created.

—O Output the two values to the console.

Note: This is an example of an implicit conversion.

Was this article helpful?

0 0

Post a comment