C# Type Conversions With Examples

12 August 2022 at 10:00 by ParTech Media - Post a comment

Many of us, on a daily basis, engage in different types of conversions. For instance, whenever we make an international transaction, we end up converting one currency to another. Similarly, we often convert our height from centimeters to feet or vice versa.

The same happens in C# programming language too. There can be scenarios in the code where conversions will be required. For instance, while running a business logic or during code handling, there will be a necessity to convert the variable from one type to another. This is nothing but type conversions.

In this blog, let us understand everything about type conversions in C# along with their syntax.

Table of contents

  1. Introduction to Type conversion
  2. Implicit type conversion
  3. Explicit type conversion
  4. Type conversion with parse()
  5. Type conversion with Convert Class
  6. Conclusion

Introduction to Type Conversion

As defined earlier, Type conversion is the process of converting one data type (int, float, double, string, etc.,) to another type. In C#, there are two basic types of conversion, they are:

  • Implicit type conversion
  • Explicit type conversion Lets us go through them in detail.

Implicit type conversion

Type conversions that are automatically taken care of by the compilers are called implicit type conversions. Generally, the implicit type conversions happen from the lower memory class to the higher memory class. To understand this better, let us look into the below example -

static void Main(string[] args)
        {
            int anInteger = 12;

            double aDouble = anInteger;

            Console.WriteLine($"Value in a double variable - {aDouble} and it is of type {aDouble.GetType()}");
            Console.WriteLine($"Value in an integer variable - {anInteger} and it is of type {anInteger.GetType()}");

            Console.ReadLine();
        }

In the above code, we have declared and assigned a value for an integer variable. In the next line, we have assigned the integer variable to a double variable. Now, if we print the two variable values at their type, the below output gets printed.

Did you notice something? Though we entered only an integer and assigned it to a double, the type of the variable was changed to double automatically. This is called implicit type conversion. Here, int occupies low memory, and double occupies higher memory.

Explicit type conversion

Type conversions that happen based on the user’s input in the program are called explicit type conversions. Generally, higher memory type variables that hold compatible lower memory type values can explicitly type cast to lower memory types using explicit type conversion. Let us understand this better using an example -

static void Main(string[] args)
        {
            double aDouble = 12.5;

            int anInteger = (int)aDouble;

            Console.WriteLine($"Value in a double variable - {aDouble} and it is of type {aDouble.GetType()}");
            Console.WriteLine($"Value in an integer variable - {anInteger} and it is of type {anInteger.GetType()}");

            Console.ReadLine();
        }

In the above code, we have assigned a value to a double variable with decimal points. The same variable is then explicitly converted as an int variable type in the next line. When we print the values, the following result gets printed -

Since we did explicit type conversion, a double value got converted to an integer. You can see that the type has also changed. Putting the type of the variable in a bracket before the variable or value denotes explicit type conversion.

Now, there are some in-built methods in C# which provide type conversion. Let us look into them.

Type conversion using Parse()

Type conversion with Parse is useful when we want to convert incompatible data types, which will result in an error when we do implicit/explicit type conversion. For example,

string str = "12345";

            int convertedValue = int.Parse(str);

            Console.WriteLine($"Value in a string variable - {str} and it is of type {str.GetType()}");
            Console.WriteLine($"Value in an integer variable - {convertedValue} and it is of type {convertedValue.GetType()}");

            Console.ReadLine();

The string is converted to int using the parse method in the above code. The below output provides the converted information.

Similarly, Parse can be used with bool, double, long, etc. When the parse is used, it does not handle the exception during the type conversion. So an exception is thrown immediately when the code is unable to parse the provided input. But, when we use try parse, the error is handled internally. If it fails, the default value is returned as a converted output.

Type conversion with Convert class

In the previous section, we explained parsing using the datatype class. In this section, we will take a look at how a common Convert class can be used to convert the variable/values to the required data type.

 	string str = "12345";

            int integer = Convert.ToInt32(str);
            double doublee = Convert.ToDouble(str);

            Console.WriteLine("String to int and double");
            Console.WriteLine($"Value of integer - {integer}");
            Console.WriteLine($"Value of double - {doublee}");

            int value = 0;
            int value1 = 1;

            Console.WriteLine("Int to bool");
            Console.WriteLine($"Original value - {value}, converted - {Convert.ToBoolean(value)}");
            Console.WriteLine($"Original value - {value1}, converted - {Convert.ToBoolean(value1)}");

The above is a code sample that provides code to convert string to int and double using the Convert class. Similarly, conversion of int to boolean using the same convert class happens. The below output gets generated on running the above code.

Likewise, it is possible to convert int to string, double, long, bool, and string to other data types and so on using the Convert class.

Conclusion

In this post, we have covered in detail everything about implicit, explicit, parse and convert class type conversion that is available in C# programming language. Use them in your project next time and experience the usefulness of this intuitive feature of C#.

Latest