Implicit Operator in C#

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.

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.

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café