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#

Method

Conversion

ToBoolean

Converts a type to a Boolean value, where possible

ToByte

Converts a type to a byte

ToChar

Converts a type to a single Unicode character, where possible

ToDateTime

Converts a type (integer or string type) to date-time structures

ToDecimal

Converts a floating point or integer type to a decimal type

ToDouble

Converts a type to a double type

ToInt16

Converts a type to a 16-bit integer

ToInt32

Converts a type to a 32-bit integer

ToInt64

Converts a type to a 64-bit integer

ToByte

Converts a type to a signed byte type

ToSingle

Converts a type to a small floating point number

ToString

Converts a type to a string

ToType

Converts a type to a specified type

ToUInt16

Converts a type to an unsigned int type

ToUInt32

Converts a type to an unsigned long type

ToUInt64

Converts a type to an unsigned big integer

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