DEV Community

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

Posted on • Originally published at rmauro.dev on

2

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more