DEV Community

Cover image for Define Implicit and Explicit Operator - C# Tips
Ricardo
Ricardo

Posted on • Originally published at rmauro.dev on

Define Implicit and Explicit Operator - C# Tips

C# allow us to define Implicit and Explicit operators. Unlike casting Implicit and Explicit operators defines how C# should behave when encountering a equals sign.

Implicit operator execution can be invoke when assigning a variable or calling a method.

To use Explicit operator we should do the same as casting an object. It's similar to a cast an object.

public record class Email(string Value)
{
    //define implicit operator
    public static implicit operator string(Email value) 
      => value.Value;

    //define implicit operator
    public static implicit operator byte[](Email value) 
      => Encoding.UTF8.GetBytes(value.Value);

    //define explict operator
    public static explicit operator Email(string value) 
      => new Email(value);
}
Enter fullscreen mode Exit fullscreen mode

Define custom operators on Record Class

To define a implicit/explicit we need to make use of "operator", "implicit" or "explicit" keywords.

The following example demonstrate the use of both operators.

Email email = new("rmauro@rmauro.dev");

//use implicit operator. This is not a cast
string stringEmail = email;

Email secondEmail = (Email)stringEmail;

//output rmauro@rmauro.dev
System.Console.WriteLine(stringEmail); 
System.Console.WriteLine(secondEmail.Value.ToString());
Enter fullscreen mode Exit fullscreen mode

Making use of defined Operators

The explicit conversion is similar to a cast operation. We make visible the type to which we will convert the object. The implicit operator is less visible and difficult to understand if you don’t know it exists.

Top comments (0)