C# Type Conversions

We know the data type of a variable cannot be changed after it is declared. However, we can convert the data type of a value to the same data type of the vairable and then assign the value to it. We called this as data type conversions.

In C#, we have lots of methods to convert data from one type value to another. In this section, we will introduce 2 basic data type conversions. One is implicit conversion and the other is explicit conversions.

  • There is no special syntax required.
  • The conversion is type safe and naturally happened.
  • There is no data lost after the conversion.
  • It happens from smaller integral types to larger one or from derived classes to base classes.

Example:

1
2
3
byte b = 12;
int i = b;
object o = 20;
  • Line 1: Declare a byte variable b and assign initial value 12.
  • Line 2: Declare a int variable i and implicit convert byte value to int value and assign it to i.
  • Line 3: 20 is an integer and belongs to System.Int32. This statement implicit convert System.Int32 to object and assign it to the variable o.
  • A cast operator is needed.
  • The cast is required if there is data loss after conversion.
  • It is needed to convert from larger integral types to smaller one or from base classes to derived classes.
  • The syntax is shown as follows.
(Cast Data Type) <Data Value>

Example:

1
2
long l = 500;
int i = (int) l;

In the above line 2, long variable l is cast to int without any data loss.

Note Note
A value is assigned to a variable. If the variable are incompatible with the type of the value, an error message will be issued.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;

namespace TypeConversion
{
    class Program
    {
        static void Main(string[] args)
        {
            double i = 77.7;
            int j = (int)i;
            Console.WriteLine("j={0}", j);

            object oo = "This is a string";
            string ss = (string)oo;
            Console.WriteLine("ss={0}", ss);

            //int p = (int)ss;
            //int p = (int)oo;

            Console.Read();
        }
    }
}

Output

j=77
ss=This is a string
  • Line 9: Declare a double variable i.
  • Line 10: Cast double to int 77. There is a data loss here.
  • Line 13: Implicit convert a string to an object. Because System.String is the derived class of System.Object.
  • Line 13: Cast the object back to string.
  • Line 17-18: Comment out because string cannot convert to integer in any cases.