2 min read

The Magic of Implicit and Explicit C# Conversion Operators: How to Handle It

The Magic of Implicit and Explicit C# Conversion Operators: How to Handle It

In 2015, I wrote an article about C# implicit operators, which are, in my opinion, extremely useful for simplifying our cast object work. Today, I plan to update the sample context with real-life examples of where you can apply this approach.

Implicit Operators

Is a conversion operator that automatically converts one type to another without the need for explicit casting. The syntax for defining an implicit operator is as follows:

public static implicit operator TargetType(SourceType source)
{
    // convert source to target and return
}
Here, TargetType is the type to which the conversion is being performed and SourceType is the type from which the conversion is being performed.

Implementation

Let's take a look at some examples to see how implicit operators work.

First, we must create an entity class called User.

class User
{
  public Guid Id { get; set; }

  public String Name { get; set; }

  public String Email { get; set; }

  public Boolean Active { get; set; }

  public DateTime InsertedAt { get; set; }
}

Then we must construct some sort of model, DTO, or whatever, and implement implicit operator conversion.

class UserCredentials
{
  public string Id { get; private set; }

  public string Name { get; private set; }

  public static implicit operator UserCredentials(User user)
  {
    if (user == null) return null;

    return new UserCredentials()
    {
      Id = user.Id.ToString(),
      Name = user.Name
    };
  }
}

Testing

It is now time to put implicit conversion to the test.

User user = new User()
{
    Id = Guid.NewGuid(),
    Name = "William",
    Email = "[email protected]",
    Active = true,
    InsertedAt = DateTime.Now
};

UserCredentials credentials = user;

We can also use explicit conversion.

var credentials = (UserCredentials) user;

Arithmetic operation

Following the image in the post, we can cast using arithmetic operations.

class Wine
{
  public override string ToString() => "🍷";
}

class Foot
{
  public override string ToString() => "🦶";
}

class Grape
{
  public static Wine operator +(Grape grape, Foot foot) => new Wine();
  public override string ToString() => "🍇";
}

Wine wine = new Grape() + new Foot();

Console.WriteLine(wine.ToString());
// > 🍷

Final thoughts

If you prefer, you can clone the repository

Implicit operators can be very useful for creating a more intuitive applications for your custom types, as well as for reducing the amount of code required to perform type conversions. However, they must be used with caution to ensure that the resulting code is clear and easy to understand.

Your kernel has been updated; see you later.