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.
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)
- {
- // Creating object of Derived class
- Derived derived = new Derived();
- // Implicit type as converting from Derived to Base class
- Base b = derived;
- // A variable 'value_Int' of int type is initialised with value 100
- int value_Int = 100;
- // A variable 'value_long' of Type long is assigned with 'value_Int'
- // This is implicit conversion from smaller value to larger value
- long value_long = value_Int;
- Console.ReadKey();
- }
- }
- }

Russell KnightPosted Feb 25, 2023, 12:20 AM
I'm a bit confused about this part "...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."I would have thought the derived class would have more data than the base class as it not only inherits all members of the base class but can contain it's own additional members. What happens if class Derived also has an int count = 0; member? When we implicitly convert it to the Base class wouldn't we lose that member as it doesn't exist on the Base class? I think your example could benefit from demonstrating a Derived class with additional members.