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);
}
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());
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)