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 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. Both classes for simplicity of our example both class only contain one field, a boolean value named fullAccess. How would can we use implicit conversion to help us simplify the process of converting from one to another?


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.


Leave a Reply