Explicit and Implicit conversion

Explicit operator

While digging into some legacy code at work, I found ‘explicit operator‘ is used in some classes. Explicit operator allow casting (or conversion) from one class to another. If you have 2 different classes, you cannot cast one to another, you’ll get a compile error. i.e

 

Now, if you add explicit operator, you can cast from one class to another like above.

No more compile error in Visual Studio

Implicit operator

You can also use implicit operator to allow conversion from one class to another. The difference from explicit operator is that you can assign one class to another and don’t have to use any cast expressions.

Without implicit operator, you get compile error

Now with implicit operator

No more compile error in Visual Studio

In my opinion, I would not use either implicit or explicit to convert from one class to another. If I need to convert all the properties from one class to another, I would use Mapper. If you want to convert to another class using only some properties, create a function or extension method. i.e

 

Like this post?

Leave a Reply

Your email address will not be published. Required fields are marked *