It's very common to face a scenario where we need to map from one class to another, and in .NET we can use several methods, such as casting or manually creating mappers for each type.
In this post, we are going to see another way to achieve our final goal: converting from one type to another. But we won't get into a discussion about which approach is better or worse.
1 - implicit keyword in C#
As we have mentioned, with an implicit operator we can convert from one type to another. To do this, we need to create a static method.
- Note: For this example, we are going to work with the code found in the Railway Oriented programming library on GitHub.
public struct Result<T>
{
public static implicit operator Result<T>(T value) => new Result<T>(value, HttpStatusCode.Accepted);
}
At first glance it looks like a normal method that simply does mapping, but it's not. That's because you don't have to instantiate or call it each time you want to do such mapping; instead, it's set up automatically at compile time.
2 - Practical Example
In the code, we work with the Result<T>
type, which uses the implicit operator. From our generic type T
to Result<T>
.
So what does this mean?
It means that in our code we can convert a T
value to Result<T>
simply by assigning the value:
int originalValue = 1;
Result<int> result = originalValue;
Or the most common case, returning it as a result from a method:
public Result<int> EjemploImplicitOperator()
{
//Resto del código
int simulacionResultado = 1;
return simulacionResultado;
}
In both cases, we are converting an int
object into a Result<int>
without having to create or call a mapper or a cast, since it's called automatically.
Conclusion
In this post, we've seen how to use the implicit operator, which is very common in open source projects but not in our daily work.
If there is any problem you can add a comment bellow or contact me in the website's contact form