Custom Implicit and Explicit type conversions in C#

csharpWe all know what type casting is. It’s converting from one type to the other. But what exactly is implicit type casting?

Well implicit type casting is a feature of C# that helps you convert instances of custom Classes you created from one to another.


Now let’s say that  we have a class named Root and a Class named Jailbreak. For simplicity of our example both classes only contain one field, a boolean value named fullAccess.
First let’s take a look at our classes shall we?

 
So you can see they have on slight difference. Root class has only a public boolean field while Jailbreak class has a public get only property and a constructor to set that property.
How can we use implicit conversion to help us simplify the process of converting from one to another?
Well first, we need to define in our classes how they should behave in these situations.

And now to make use of implicit type conversion all we have to do is the following.

And that’s all Folks!! Nothing more to do here. When implementing the implicit type conversion methods within the class, the rest is automated.

Now for explicit conversions. 
We can implement explicit conversions from our custom object to anything else just like with implicit conversions. The only difference is we have to type explicit and not implicit when we are defining it like so

and to perform the conversion we simply do

That’s all there is to it.

 

Just a final note, you can always have more than one implicit or explicit type conversions in a single class. You do not need to have only one. As long as you do not have more than one for the same type you are converting to.

 

Please follow and like us:

Leave a Reply