Implicit and Explicit Conversions in C#

In this article, we will look into the conversions that are required when you assign a value of one data type to another data type. C# is a strongly typed language, it checks the data type of a variable when you assign a value to it. We will briefly describe implicit and explicit conversions.


Implicit Conversion


When you assign a value of one variable to another variable, C# compiler automatically converts that for you if -

1. They are compatible
2. There is no loss of information.

Let's take an example to make it more clear - int and short are compatible as they both are used for integer values. Now when you assign a short variable to an integer variable then it will be converted automatically for you as short values can be easily stored in an integer variable. Why? Integer takes 4 bytes and Short takes 2 bytes (Refer Data Types). Values can be accommodated in integer variable easily.

using System;

class Program
{
    static void Main(String[] args)
    {
        short shortNumber = 3; // short takes 2 BYTES
        int intNumber = shortNumber; // int takes 4 BYTES - Implicit Conversion
        Console.WriteLine(intNumber); //Outputs 3

        //Even you choose the max value of short it will not show any error
        shortNumber = short.MaxValue;
        intNumber = shortNumber;
        Console.WriteLine(intNumber); //Outputs 32767

        Console.ReadKey();
    }
}

Since there is no loss of information and types are compatible - implicit conversion is done for you by the compiler. In short, if the data type of the target variable is larger than your current data type, implicit conversion will be done by the compiler itself.

Explicit Conversion


In this case, you explicitly make a request to the compiler to convert one value to another by using either a Cast operator or Convert classes. To make it more clear - take one e.g. Let's put an integer variable into a short variable. Compiler will report an error that it cannot implicitly convert that for you. Even if you know that the value lies in the range of the data type, compiler still reports the error because as per compiler it can cause information loss. For this, you need to use a cast operator or Convert classes.

cheezycode-explicit-conversion-error.png


To solve this problem, as compiler indicates - we need to use cast operator. You can also use Convert classes. Refer below program for the same -

    using System;
    
    class Program
    {
        static void Main(String[] args)
        {
            int intNumber = 3; 
            short shortNumber = (short) intNumber;
            Console.WriteLine(shortNumber); // PRINTS 3
    
            // or you can use Convert classes
            shortNumber = Convert.ToInt16(intNumber);
            Console.WriteLine(shortNumber); // PRINTS 3

            Console.ReadKey();
        }
    }


Even if the types are compatible, there could be some loss of information if you assign a larger value into a smaller variable because it cannot accommodate that value. So compiler will not do such conversions on it's own. You need to say that to a compiler that -

Yes! You are aware of the fact that these data types do not match but still you want the value to be stored in a particular variable. At run-time, if you face any error or exception doing the required conversion then raise that exception, my program will take care of it.

It is necessary that you must use proper data types and always take care of your conversions. Improper conversions can cause unnecessary errors at run-time. One such example where conversions can cause issues is - Banking Applications - Fractional values in float makes a huge difference and they have to be exact. Conversion of these values must be done with care.

String Conversions


There are scenarios where you want to convert strings like "1" or "3.14" or "true" to other data types. In these cases, you cannot use cast operator because they are not compatible. String is altogether a different data type which does not match with other primitive data types. For these cases, you use Convert classes.

using System;
    
    class Program
    {
        static void Main(String[] args)
        {
            String strInteger = "1";
            String strFloat = "3.14";
            String strBoolean = "true";

            int convertedInt = Convert.ToInt32(strInteger); // For Int- 4bytes use - ToInt32()
            float convertedFloat = Convert.ToSingle(strFloat); //For Float use - ToSingle()
            bool convertedBoolean = Convert.ToBoolean(strBoolean); // For Boolean - ToBoolean()

            Console.WriteLine("Integer - " + convertedInt); // PRINTS 1
            Console.WriteLine("Float - " + convertedFloat); // PRINTS 3.14
            Console.WriteLine("Boolean - " + convertedBoolean); //PRINTS True
            Console.ReadKey();
        }
    }

In the above cases, if the string you passed as a parameter cannot be converted, it will throw exception. For e.g. if you have strInteger = "garbage" - exception will be thrown as shown below -


cheezycode-string-conversion-error


In what scenarios this will occur?


In scenarios, where you take input from the user. You prompt the user to enter his/her age. Age is always an integer. But Console.ReadLine returns this as a String Object or if you have a windows application, Textbox also returns the input as String. You need to convert that to an integer variable. For this, you need Convert classes. But, it depends on the user, if he/she enters something else, your program should not throw exception and close abruptly. Your program should show a proper message that - "Please Enter Proper Value". For this you can use TryParse as shown below.

Another safest approach to convert string containing numbers and booleans - TryParse

Use of TryParse is the preferable approach to convert strings because as it's name suggests - it first tries to convert that string - if successful, returns the output. It does not throw any exceptions. So try using this whenever you need to convert strings. You must have seen the example of this in our previous post. Below program uses out - which will be explained in future post. Just refer the syntax.

using System;
    
    class Program
    {
        static void Main(String[] args)
        {
            int age;
            Console.WriteLine("Enter Your Age - ");
            string strAge = Console.ReadLine();
            if (int.TryParse(strAge, out age)) 
            {
                Console.WriteLine("Input is in correct format -" + age);
            }
            else
            {
                Console.WriteLine("Please enter the correct value");
            }
            Console.ReadKey();
        }
    }

Output -


cheezycode-try-parse



Let us know if you have any query or concerns. Happy Reading (refer full series here - C# Tutorial Index)




Comments

Popular posts from this blog

Create Android Apps - Getting Started

Polymorphism in Kotlin With Example