In this article, I am going to share with you about Type Casting and its types in C#.
What is Type Casting or Type Conversion in C#?
Type Conversion is the conversion of one data type into another. Type Conversion is also called Type Casting.
In C#, there are two types of Type Conversion -
Implicit Type Conversion
Implicit conversion is the conversion when we convert the smaller data type into a larger one and when converting from derived to a base class. As we are converting from smaller data type to larger, there will be no loss of data. It is performed automatically by the compiler. Implicit type conversion of derived to a base class is known as Upcasting. Have a look at the example below.
- using System;
-
- namespace Tutpoint
- {
- class Program
- {
- class Base
- {
- string Text = "Hello.. Base Class";
- }
- class Derived : Base
- {
- string Text = "Hello.. Derived Class";
- }
- static void Main(string[] args)
- {
-
- Derived derived = new Derived();
-
- Base b = derived;
-
-
- int value_Int = 100;
-
-
- long value_long = value_Int;
-
- Console.ReadKey();
- }
- }
- }
Here, we created two classes 'Base' and 'Derived' inside a class 'Program'. The 'Derived' class inherits 'Base' class. As we know in Implicit conversion, we are converting from smaller type to larger one; also, converting from Derived to Base class. Object 'base' of Base class is assigned to the object 'derived' from Derived class. In the second part, we assigned a value of 'int' type to 'long' type. This is all about Implicit Conversion.
Explicit type conversion
Explicit conversion is the conversion when we convert the larger data type into a smaller one and when converting from base to derived class. As we are converting from larger data type to smaller, there may be the loss of some part of data. This can be performed by cast operator. Explicit type conversion of the base to the derived class is known as Downcasting. Have a look at the example below.
- using System;
-
- namespace Tutpoint
- {
- class Program
- {
- class Base
- {
- string Text = "Hello.. Base Class";
- }
- class Derived : Base
- {
- string Text = "Hello.. Derived Class";
- }
- static void Main(string[] args)
- {
-
- Base b = new Base();
-
- Derived derived = (Derived)b;
-
-
- int value_Int = 100;
-
-
-
- short value_short = value_Int;
-
-
- short value_shor = (short)value_Int;
- Console.ReadKey();
- }
- }
- }
Here, we created two classes 'Base' and 'Derived' inside class 'Program'. 'Derived' class inherits 'Base' class. As we know, in explicit conversion, we are converting from a larger type to smaller one and from Base to Derived class, the object 'derived' from Derived class is assigned to the object 'b' of Base class. In the second part, when we try to convert explicit type directly, an error will occur as "Cannot implicitly convert type 'int' to 'short'. An Explicit conversion exists". On next statement, this is achieved using cast operator. This is all about Explicit Conversion.