1.8: Type Conversion

TYPE CONVERSION

In this module we'll discuss type conversion, that is, turning one type into another.

File Location

  1. Right click on the solution you made in the first module

  2. Go to Add > New Project and select Console App (.NET Framework)

  3. Name it 0.01_TypeConversion

  4. Write your code for this module within Program.cs of that project.

  5. Set this project as the start up project.

Discussion

It is important to understand that your code will throw errors if data types do not match up. You will often have to use conversion methods to make them work. We use type conversion to convert one type of data to another type. It is also referred to as type casting. There are two forms of type casting in C#.

    • Implicit Type Conversion − Type of conversion performed by C# in a type-safe manner. For example, conversions from smaller to larger integral types and conversions from derived classes to base classes. Going from short to integer.

    • Explicit Type Conversion − Type of conversion that is done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.

Implicit Type Conversion Examples

    class Program
    {   
      static void Main(string[] args) 
      {
         double a = 5673.74; 
         int i;

         // cast double to int.
         i = (int)d;

         Console.WriteLine(i);
      }
   }

When this program is printed to the console, it returns us an int of 5673. What kinds of problems might this create?

Here is another example of implicit type conversion. These lines of code convert an int to a float.

    class Program
    {   
      static void Main(string[] args)
      {            
            int i = 1000;
            float f = i;
            //Implicit conversion happens. Float is a bigger data type than int.

            Console.WriteLine(f);
      }
   }

Explicit Type Conversion Examples

Below are the different conversion methods built into C#

The following examples demonstrate using the built in conversion method ToString()

    class Program {

      static void Main(string[] args)
      {
         int i = 75;
         bool b = true;

         Console.WriteLine(i.ToString());
         Console.WriteLine(b.ToString());
      }
   }

Parse

Parse() is a static method(more on methods later) we access on the int type. It returns an integer upon success:

    class Program {

      static void Main(string[] args)
      {
        string text = "500";
        int num = int.Parse(text);
        Console.WriteLine(num);
      }
   }

This will print 500 and its type will now be an int.

Conversion

In the example below, Visual Studio will give you an error. Any info coming from Console.ReadLine() is a string. However, if we want to do any math or use > or < etc. when doing things with the response, we need the answer to be an int.

 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("How are you today on a scale of 1-10?");
            int feelingNumber = Console.ReadLine();
        }
    }

When we run into situations like this, methods that are useful are Parse(), TryParse(), and Convert.ToInt32().

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("How are you today on a scale of 1-10?");
            int feelingNumber = Convert.ToInt32(Console.ReadLine());

            if (feelingNumber >= 8 && feelingNumber <= 10)
            {
                Console.WriteLine("Great!");
            }

            else if (feelingNumber == 5)
            {
                Console.WriteLine("eh");
            }

            else if (feelingNumber <= 4 && feelingNumber >= 1)
            {
                Console.WriteLine("sorry");
            }

            else
            {
                Console.WriteLine("Enter a number between 1 and 10");
            }
        }
    }

Now that we've converted the string to an int, we can use math in our conditional statements.

Back to string

You may also run into situations where you need to do the opposite. Convert an int to a string. One way of doing this is using a ToString() method.

 class Program
    {
        static void Main(string[] args)
        {
            int myNum = 500;
            string myString = myNum.ToString();
            Console.WriteLine(myString);
        }
    }

CONVERSION CHALLENGE

Practice converting ints to strings and strings to ints. Create at least 3 of each.

Next: Booleans

Last updated