top of page

Implicit Operator in C#

In C# language (and others) there is plenty of scenarios where a Mapping process is necessary between different classes. It can be achieved in many distinct ways, such as the use of AutoMapper, manual property correlations, and casts operations. The purpose of this post is not to have a debate around what is the best method as it depends on each scenario. However, the main goal in this quick article is to present a feature in C# language that not all developers are aware of how it works or maybe never seen before: implicit operator.

Example

Imagine the scenario where you have a hypothetical class called “Customer”, with the following sample properties:

In complement to that, let's state that we would need a Customer DTO class for a Web API return, that needs only Id and Full Name (instead of the individual pieces of the name), like the example below:

We want to map the properties correctly, but without mapping each property individually in every place the mapping would need to be applied. In order to achieve this “automatic” cast between the two classes, transparent to the “caller”, it is possible to use the “implicit” operator in the source class (Customer), in a static field, as it follows:



At the first moment, it seems to be a normal static field, but it is not! Considering the field returns an instance of CustomerDTO, populating with a customer object, in case we want to cast a Customer object to CustomerDTO, we can just assign the CustomerDTO object with a Customer one, as the example below:

Note that it was not necessary to explictly call a method for conversion or making any cast operation. It recognizes automatically what needs to be done, transparently. That is the result of the Console.WriteLine:

I do like the simplicity of it. If you have seen something similar in legacy projects or open-source libraries and did not understand what was happening, now I hope it is clear for you. And now you have an “extra tool” to use in the cases where you think that is going to be helpful in order to simplify your code.

Conclusion

Thank you for reading this quick article until the end. If you have any questions or comments, please leave it here. I’ll be glad to chat about it.



Source: Medium


The Tech Platform

0 comments

Kommentare


bottom of page