Converting One Data Type to Another

Throughout your application, you will need to convert from one data type to another. Even the most straightforward application needs to take in user input as a string and convert the value to integers for calculations or dates and times for time-span operation.



This blog post will try to explain some of the conventional techniques to use when converting types, as well as the differences between them.


Parse Method

The Parse method is straightforward to use when converting a string value to another data type. To perform the conversion, you use the Parse method of the System object that represents the data type you need your string value to become. Parsing can be done by providing string literals or a variable with a string value already assigned.

 DateTime myBirtday = DateTime.Parse("01/23/2000");
 DateTime sonBirthday = DateTime.Parse("03/14/2008 1:17:25 PM");
 
 int computerAge = int.Parse("49"); 
 long planetAge = long.Parse("4500000000");
 
 Console.WriteLine("How old are you?");
 string userInput = Console.ReadLine();
 int userAge = int.Parse(userInput); 

This code parses a mix of literals and variables into the desired data type.


Parsing Numbers

When parsing strings into integers, there is is a wide variety of acceptable formats for providing numerical values in a string. Commas are often used to separate thousands. Parenthesis sometimes represents a negative value. A dollar sign will occasionally accompany a currency value. If these symbols and characters are used in a simple Parse method call, the application will throw an error. Luckily most numeric data types allow you to provide a NumberStyle when calling the Parse method.


NumberStyles exist in the System.Globalization namespace, so make sure you add it to your “using” statements.


Some NumberStyles are

  • AllowThousands – indicates that commas may be used to separate thousands

  • AllowCurrencyValue – indicates that the string may contain a currency symbol

  • AllowLeadingSign – permits the string to begin with a symbol

  • AllowLeadingWhite – permits the string to begin with whitespace

  • AllowParentheses – indicates that parentheses may be used in the string

 long planetAge = long.Parse("4,500,000,000",NumberStyles.AllowThousands); 
 int yearlySalary = int.Parse("$45000", NumberStyles.AllowCurrencySymbol);
 int travelExpense = int.Parse("(527)", NumberStyles.AllowParentheses);

Problems with Parse

Although the Parse method provides some useful functionality, there are some limitations. First, and foremost, is the reliance on a valid string variable being provided. If a null value is provided, a FormatException error occurs. The same thing occurs if an invalid string value is given.


Another downside to the Parse method is that it only converts string values to the new data type.


TryParse Method

To avoid any invalid input causing the application to crash when using the Parse method, you can use the TryParse method. TryParse will do what the name implies and try to parse the provided value into the desired data type.

 bool isValidInput;
 int validInteger = -1; 
 isValidInput = int.TryParse("49", out validInteger);
 isValidInput = int.TryParse("Scott", out validInteger);

As you can see, there are a few more steps when working with TryParse.


The TryParse method will return a Boolean value (true/false) on whether or not the input can be parsed into the new data type. In this code sample, when Visual Studio tries to parse “49,” the value of isValidInput will be TRUE.


When “Scott” gets parsed, the value of isValidInput will be FALSE. Remember, TryParse is asking whether or not the value can be parsed. The answer to that question is always TRUE or FALSE.


Out Keyword

So how do you get the actual value if parsing is possible? That is where the “out” keyword comes into play. You will learn more about method return types and the different parameter types in the blog posts about methods. Until you get that understanding, I’m going to simplify the explanation here greatly.


Think of using a method as a way of asking a question. The “return” of the method is the answer to the question.


As an example, when you use the Console.ReadLine method, you are asking, “please read the line the user typed and give it to me as a string value.” The answer comes back as a string representation of the text entered by the user.


Sometimes the methods you use don’t have an answer. When you use Console.WriteLine, you are asking, “please write this information to the console window.” There is no answer to that question, so it just occurs. If there were a problem fulfilling that request, the application would crash.


A method can not provide two separate answers. When you ask TryParse, “can this value be converted properly?” the only possible answer are TRUE or FALSE. Sometimes, however, a method will spit out some additional pieces of information. This information does not answer the question be asked; it’s just some information you may want to use.


It’s like when you ask your grandfather to pass the potatoes at Thanksgiving, he will hand you the potatoes, but sometime he will lecture you on the length of your hair, or regal you with a story of his youth.


Since the additional information is not the answer to the question, you need somewhere to store the data that gets spit out. The “out” keyword is used for situations like this. You create a location for the information but declaring a variable and initializing it with a value. You then use “out” to let the method know what variable will hold the “spit out” information. If the answer to the TryParse question is TRUE, then the converted value will be stored in the out variable.

 bool isValidInput;
 int validInteger = -1; 
 isValidInput = int.TryParse("49", out validInteger);
 Console.WriteLine($"The answer to the TryParse question is {isValidInput}.");
 Console.WriteLine($"The value of validInteger is {validInteger}");

In this segment of code a variable (isValidInput) is created to store the TRUE/FALSE answer. A second variable (validInteger) is used to stored the additional information that may be spit out of the method. When this code is executed, isValidInput equals TRUE, and validInteger has the value of 49.

If the answer to the TryParse question is FALSE, the method will spit out the default value for that data type.

 bool isValidInput;
 int validInteger = -1; 
 isValidInput = int.TryParse("Scott", out validInteger);
 Console.WriteLine($"The answer to the TryParse question is {isValidInput}.");
  Console.WriteLine($"The value of validInteger is {validInteger}");

When this code is executed, isValidInput equals False, and validInteger has the value of 0.


Convert Class

The methods of the Convert class allows you to attempt converting any data type into the desired data type. It works with string values but is not restricted to working only with string, the way the Parse method is. The Convert class belongs to the System namespace, so it needs no particular set up to use.


You type in the Convert object name, and you are provided with a list of potential methods to use for conversion.

  • ToInt32

  • ToLong

  • ToDateTime

  • ToBoolean

  • ToDouble

These methods work just fine with string values.

 DateTime myBirtday = Convert.ToDateTime("01/23/2000");
 DateTime sonBirthday = Convert.ToDateTime("03/14/2008 1:17:25 PM");
 
 int computerAge = Convert.ToInt32("49");
 long planetAge = Convert.ToInt64("4500000000");
 
 Console.WriteLine("How old are you?");
  string userInput = Console.ReadLine();
 int userAge = Convert.ToInt32(userInput);

Another benefit the Convert method has over the Parse method is that Convert will not throw an error if a null value is supplied. If you attempt to Convert a null value, the method will return the default value for that type.

 Console.WriteLine(Convert.ToInt32(null)); // Displays 0
 Console.WriteLine(Convert.ToDateTime(null)); // Displays 1/1/0001 12:00:00 AM

Converting Numerical Types

In addition to using string values, the Convert class allows you to convert numerical values from one data type to another. You just need to be very careful when doing so. Since an integer is a whole number, if you convert a number with a decimal value into an integer, any digits after the decimal point will be cut off. The number will not be rounded.

 int pizzaPrice = 10;
 double tip = pizzaPrice * .15;
 int priceTotal = Convert.ToInt32(pizzaPrice + tip);

When this code executes, the value of priceTotal will be 11. The .50 was dropped from the value when the double 11.5 was converted to an integer.

Problems with Convert

The Convert methods allow you to attempt conversion from multiple data types. However, the values must be in the proper format. The Convert methods do not have NumberStyles that allow you to use a comma or currency symbols

 Console.WriteLine(Convert.ToInt32("10,000")); // Crashes the application
  Console.WriteLine(Convert.ToDouble("$4.56")); // Crashes the application

Casting to a Type

Sometimes you will be writing an application where you know, definitively, that a value will convert to another type, and you don’t want the overhead of calling the Parse or Convert methods. In that situation, you can do an “explicit cast.” An explicit cast will convert the value of one type into another type without going through any method calls.

To perform a cast, you surround the new type with parentheses and follow it with the value to be converted.

 double costOfDinner = 45.87;
 int newCost = (int)costOfDinner;

If you remember the warning from earlier in this post. Converting a double to an integer will cause the digits after the decimal to be truncated. So be careful when you are casting to an integer.


Casting an integer to other numeric types, however, is very convenient and often necessary. For example, if you were writing a tip calculator application, you would ask the user to provide the percentage of the bill they’d like to give as a tip. Users generally see this as an integer value. If you ask them what percentage they will enter a whole number.


 double costOfDinner;
 Console.WriteLine("What is the cost of dinner?");
 costOfDinner = double.Parse(Console.ReadLine());
 
 int desiredTip;
 Console.WriteLine("What percentage of the bill will you tip (1-100)?");
 desiredTip = int.Parse(Console.ReadLine());

Now to get the actual tip percentage, you will need to convert that value into a double.

 double tipPercentage;
 tipPercentage = desiredTip / 100;

The problem with this code is that tipPercentage will equal 0 when this code is executed. This occurs because Visual Studio sees that desiredTip is an Integer, so the resolution of the calculation will be treated as an integer as well. All decimal values will be truncated, even though tipPercentage has a double data type.


You need Visual Studio to see desiredTip as a double before the calculation occurs. You don’t want to change the data type of the variable; otherwise, that could allow data you don’t want. You just need to cast that value as a double for the calculation.

 tipPercentage = (double) desiredTip / 100;

By casting the value as a double in the calculation, you are guaranteed that result will be a decimal value.

55 views0 comments

Recent Posts

See All