In this tutorial, we will learn the various methods that we can use to safely convert the objects and primitive types.
Implicit Conversion
One of the most common type of conversion in C# is the implicit conversion. This conversion occurs automatically when a smaller type is assigned to a large type. For example, an integer to a float can occur implicitly as follows:
float f = i;
Console.WriteLine(f);
Since a float is capable of holding a larger range of values than an integer, the conversion happens automatically without loss of data.
Explicit Conversion (Manual)
The second type of conversion is an explicit conversion. This occurs when you need to convert a larger type to a smaller type.
We do this by placing the desired type in parentheses before the variable.
int i = (int)f;
Console.WriteLine(i);
This should explicitly convert the provided value into an integer from a float.
Object Conversion
There are various types of object conversion in C# as described in the following sections:
Upcasting
Up conversion refers to the process of converting a derived class object to a base class. This happens implicitly as shown in the following example:
class Derived : Base { }
Derived derived = new Derived();
Base baseObj = derived;
In this case, the derived object from the “Derived” class is upcasted automatically to baseObj from the “Base” class.
Downcasting
Downcasting is the opposite of upcasting. It converts an object from a base class to a derived class. As you can guess, this operator requires an explicit conversion as follows:
Derived derived = (Derived)baseObj;
Safe Object Conversion
We can also use the “as” operator to safely convert the objects. In this case, if the conversion fails, it returns null instead of throwing an exception as follows:
Derived derived = baseObj as Derived;
if (derived != null)
{
Console.WriteLine("Convert Successful");
}
In this case, if we can convert the base object to the derived object. It represents a successful convert instead of null.
The “Is” Operator
Before performing an object conversion operation, it is good to check if an object is compatible with the specified type. We can accomplish this using the “is” operator as follows:
if (baseObj is Derived)
{
Derived derived = (Derived)baseObj;
Console.WriteLine("Convert Successful");
}
The operator returns “true” if the convert is supported and returns “false” otherwise.
Conclusion
In this tutorial, we explored all you need to know about conversion in both primitive types and objects in C# using the explicit and implicit conversion types.