C# Type Conversion


This entry is part 3 of 4 in the series C# Primitives and Expressions

What is type conversion? Mosh Hamedani has a short instructional video up at Udemy.com. It’s the tenth video at his beginner series.

There are two types of conversions: implicit and explicit. We need to understand when types are compatible and not compatible.

We need to understand bits and bytes. Eight bits are in a byte.

Convert and Parse

The Convert class is part of the .NET Framework and it is defined in the System namespace. There are 17 methods available and they all start with “To”. Int32 is a .NET Framework type that maps to an integer type in C#. Int16 means 16 bits which is 2 bytes which translates to short in C#. Here are some examples of the methods in the Covert class: ToBype(), ToInt16(), ToInt32() and ToInt64().

All of the primitive types like int, long, float , boolean have a Parse method. Parse takes in a string and tries to convert it to the type using the Parse method.

using System;
namespace TypeConversion
{
    class Program
    {
        static void Main(string[] args)
        {
            byte b = 1;  // has 1 bytes, int has 4 bytes. max 255.
            int i = b;  // implicit type conversion
            var number = "1234";

            i = 1;
            //b = i;  // will not compile - cannot implicitly convert
            byte b2 = (byte)i;  // explicit type converion using casting

            i = 1000;
            b = (byte)i; // value of b is 232 because of data loss

            float f = 1.0f;
            int i2 = (int)f;  // explicit

            // Non-compatible types: string and int are not compatible
            // We cannot use explict casting: int i3 = (int)s;  Will not compile
            // We need to use Convert class or Parse method. Which one?
            string s = "m";
            int i3 = Convert.ToInt32(s);
            int i4 = int.Parse(s);

            //int i5 = (int)number; // ERROR cannot cast string to int
            int i5 = Convert.ToInt32(number);  // this works fine.
            int i6 = Convert.ToInt32("1234");  // this works fine.
            // byte b3 = Convert.ToByte("1234");  // ERROR Unhandled Exception at run time.
        }
    }
}

Try Catch

Now let’s dig a little deeper into the last example in the code listing above.

using System;
namespace TypeConversion2
{
    class Program
    {
        static void Main(string[] args)
        {
            // try is a code snippet
            // let us handle the exception to prevent .NET runtime
            // handling the exception and thereby crashing our program
            try
            {
                var number = "1234";
                byte b = Convert.ToByte(number);
                Console.WriteLine(b);
            }
            catch (Exception)
            {  // we get here!
                Console.WriteLine("The number could not be converted to a byte.");
            }
            try
            {
                string str = "true";
                bool b = Convert.ToBoolean(str);  // this works
                Console.WriteLine(b);  // output is: True
            }
            catch (Exception)
            {
                // we do NOT end up here.
                Console.WriteLine("error");
            }
        }
    }
}
Series Navigation<< C# ExpressionsC# Operators >>