C# Data type Conversion

C# Data type conversion is the concept that is helpful when we want to store the value of one data type variable into a variable of another datatype.

C# is a statically typed language. It means a variable declared with one data type cannot be declared again to store values of another datatype without converting that type into variable’s type.

When variable i is declared of type integer

int i;

We cannot store string value in i

i= “hai”;

The C# compiler will throw an error saying “cannot implicitly convert type ‘string’ to ‘int’.

However, we might sometimes come across situations where we need to copy the value of one type into a variable or parameter of a method whose datatype is different.

That is, we may have an integer variable, which we need to pass its value to a method whose parameter is of type float or double.

C# Datatype Conversion Examples

This operation on datatypes is generally called as type conversions in C#.

In C#, two different types of conversions happen in real-time.

  1. Implicit Conversion
  2. Explicit Conversion

C# Implicit Conversion

Implicit in the sense, this conversion is type-safe and is done automatically by the C# compiler only in the following cases.

  1. If there is no loss of information when the conversion happens.
  2. If there is no chance of throwing exceptions during the conversion.

Let us see an example to understand it better.

For example, converting an int to a float has no information loss, and no exception will throw.

int i = 50;

float f = i;

The above statements are valid because, when executed, they won’t have any loss of information due to having a much bigger size for the float than int.

But if we take the reverse case like, for example.

float f = 234.76;

int i = f;

These statements will get a compile-time error when executed, saying “cannot implicitly convert type ‘float’ to ‘int’ “.

The reason is during the process of storing the value of float in integer variable i there will be a loss of information. Since integer will not allow precision (digits after decimal) and there is a possibility of throwing an exception because the size of a float is much bigger than that of int.

In this situation, we need to do the explicit conversion using type cast operator or the Convert class in C#.

Let us first see using the type cast operator.

using System;

namespace CSharp_Tutorial
{
    class program
    {
        public static void Main()
        {
            float f = 234.76F;
            int i = (int)f;
            Console.WriteLine("Original Float Value = {0}", f);
            Console.WriteLine("Converted Integer Value = {0}", i);
            Console.ReadLine();
        }
    }
}

OUTPUT

C# Type Casting 1

Float variable f is holding double-precision value 234.76.

When we are trying to store it in integer variable i, we need to convert float value to int using type cast operator, which is ‘(int)’.

Since integer doesn’t hold decimal values, it will store only the integer part of the float value.

i.e., 234 is the output 

C# Type conversion using Convert class

Convert is a system-defined class for datatype conversions. The only difference in using type cast operator and the Convert class is explained in the below examples.

using System;

namespace CSharp_Tutorial
{
    class program
    {
        public static void Main()
        {
            float f = 123456778907.76F;
            int i = Convert.ToInt32(f);

            Console.WriteLine("Original Float Value = {0}", f);
            Console.WriteLine("Converted Integer Value = {0}", i);
            Console.ReadLine();
        }
    }
}

OUTPUT

C# Type Casting 2

Here we are trying to store a floating-point value, which is much bigger than the integer.

In this case, the compiler will throw an exception if we use the Convert class for typecasting. 

But if we use type cast operator, then the C# compiler will print the minimum range of the type integer.

using System;

namespace CSharp_Tutorial
{
    class program
    {
        public static void Main()
        {
            float f = 123456778907.76F;
            int i = (int)f;

            Console.WriteLine("Original Float Value = {0}", f);
            Console.WriteLine("Converted Integer Value = {0}", i);
            Console.ReadLine();
        }
    }
}

OUTPUT

C# Type Casting 3

Here we are trying to store a floating-point value, which is much bigger than the integer.

This case compiler will print the minimum range of type integer when the type cast operator is used for typecasting. 

Conversion of C# string to a number (int, float, long, etc.)

In the case when we want to convert a string value to an integer format, we have two options

  1. Parse()
  2. TryParse()

Forexample, using Parse() method, we can convert a number in string format to integer format as follows

using System;

namespace CSharp_Tutorial
{
    class program
    {
        public static void Main()
        {
            string s = "200";
            int i = int.Parse(s);

            Console.WriteLine("Original String = {0}", s);
            Console.WriteLine("Converted Integer Value = {0}", i);
            Console.ReadLine();
        }
    }
}

OUTPUT

C# Type Casting 4

Here “100” is a number but in string format, i.e., with double-quotes.

The parse method is useful to convert it to integer format and finally printed value inside the i variable.

If the number is in a string format – C# Parse Method

If the number is in a string format, using parse () throws an exception if it cannot parse the value. In comparison, TryParse() returns a bool indicating whether parsing is succeeded or failed.

If we are sure that the parse will be valid in real-time, then we use the Parse() method. Otherwise, we use the TryParse() method.

For example

using System;

namespace CSharp_Tutorial
{
    class program
    {
        public static void Main()
        {
            string s = "200ab";
            int i = int.Parse(s);

            Console.WriteLine("Original String = {0}", s);
            Console.WriteLine("Converted Integer Value = {0}", i);
            Console.ReadLine();
        }
    }
}

OUTPUT

C# Type Casting 5

Here Parse() method failed to convert. Hence it is throwing the exception.

Let us see using C# TryParse() method

TryParse() method can be called using the syntax.

Syntax:

TryParse(<string variable> out <integer variable>)

TryParse() will always return bool value, which is true if it succeeds in parsing; otherwise, it returns false.

Let us see the C# TryParse example code.

using System;

namespace CSharp_Tutorial
{
    class program
    {
        public static void Main()
        {
            string s = "200ab";
            int Result = 0;
            bool i = int.TryParse(s, out Result);
            if (i)
            {
                Console.WriteLine(i);
            }
            else
            {
                Console.WriteLine("please enter any valid number");
            }
            Console.ReadLine();
        }
    }
}

OUTPUT

C# Type Casting 6

Here s is the string variable whose value is “200ab”.

The result is the integer variable, and i is the Boolean variable to store the TryParse() result.

Since the TryParse() returns a bool, we have coded that if parsing is successful print, the Parsed result otherwise print the statement

“Please enter any valid number”.