Using Explicit Operators in Microsoft .NET to Perform Type Conversions

In Microsoft .NET, there are various approaches to converting one type to another. One such method involves using operators. By implementing an “explicit” operator, you can easily perform type conversions within your types. These operators need to be declared as public static methods. Let me demonstrate how I utilized this feature in DotNetTips.Spargine.6.Tester code and NuGet package.

In my code performance book, I conduct benchmark tests using a primary real-world type called PersonProper. PersonProper is a reference type, while there is another type called Person that is implemented as both a reference type and a value type. Both types implement the IPerson interface.

To enable the creation of a new PersonProper object from a Person value type, I implemented the explicit operator as follows:

public static explicit operator PersonProper(ValueTypes.Person person) 
   => new()
{
	Address1 = person.Address1,
	Address2 = person.Address2,
	BornOn = person.BornOn,
	CellPhone = person.CellPhone,
	City = person.City,
	Country = person.Country,
	Email = person.Email,
	FirstName = person.FirstName,
	Id = person.Id,
	HomePhone = person.HomePhone,
	LastName = person.LastName,
	PostalCode = person.PostalCode,
	State = person.State,
};

Here is an example of how to use the operator (from the unit test method).

var personVal = RandomData.GenerateValPerson<ValueTypes.Person>();
var personRef = (PersonProper)personVal;

When coding types, here are the reasons why it is good to add an explicit operator:

  1. Controlled type conversion: Explicit operators allow you to define and control how one type can be converted to another. By providing a custom conversion logic, you have full control over the conversion process, ensuring that it is performed in a specific way that meets your requirements.
  2. Enhanced type safety: By explicitly defining conversion operators, you can enforce type safety and ensure that only compatible types can be converted. This helps catch potential conversion errors at compile-time rather than runtime, reducing the risk of unintended data loss or incorrect conversions.
  3. Improved code readability: Explicit operators can make your code more readable and self-explanatory. By defining conversion logic within the types themselves, you make it clear to other developers what type conversions are available and how they can be used. This can lead to code that is easier to understand and maintain.
  4. Seamless integration with language features: Explicit operators seamlessly integrate with other language features such as casting and assignment operations. They allow you to perform explicit type conversions using familiar syntax, making the code more expressive and intuitive.
  5. Flexible integration with third-party libraries: Explicit operators can be particularly useful when integrating with third-party libraries or APIs that use different data types. By defining explicit operators, you can easily convert between types used in your code and the types expected by external components, enabling smooth interoperability.
  6. Avoiding unnecessary code duplication: Explicit operators can help avoid duplicating code for conversions between related types. Instead of writing conversion logic in multiple places throughout your codebase, you can define it once in a conversion operator, making your code more maintainable and reducing the risk of inconsistencies.

Summary

Explicit operators offer control, clarity, and type safety when performing type conversions that leads to cleaner code. I hope you give it a try.

If you would like to give Spargine a try use these links:
GitHub: https://github.com/RealDotNetDave/dotNetTips.Spargine/releases
NuGet: http://bit.ly/dotNetDaveNuGet

If you have any questions about this article, please share them in the comments below, I’d love to hear from you.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.