Goglides Dev 🌱

Cover image for How to Automatically Cast Between Types in C#
Dev Leader
Dev Leader

Posted on • Originally published at devleader.ca

How to Automatically Cast Between Types in C#

The post How to Automatically Cast Between Types in C# appeared first on Dev Leader.

To automatically cast between types in C#, we need to look at something called implicit operators in C#. In particular, we’ll need to define what are static implicit operators. By defining these on our types, we can instruct the compiler how to convert between types without the need to write explicit casting in our code.

This article will give you a quick code example of how to implement them using a practical scenario. Check it out, and let me know if you have any questions!


What are Implicit Operators in CSharp?

Implicit operators in C# are a powerful feature that allows objects of one type to be automatically converted to another type without the need for an explicit cast. They provide a way to seamlessly convert between types, making code more concise and readable.

Implicit operators are defined as special methods within a class or struct, using the implicit keyword. These methods specify the conversion from one type to another. When the compiler encounters an assignment or expression involving compatible types, it will automatically invoke the appropriate implicit operator to perform the conversion.


Code Example: Automatically Cast Between Types in CSharp

In this example, we’re going to walk through binary capacity! As software engineers, we’re always having to convert between bytes, kilobytes, megabytes, and beyond. While this is relatively straightforward, the fact that it’s not exactly a decimal conversion (i.e. multiply/divide by 1000) but instead a factor of 1024 introduces a bit of cognitive overhead.

Let’s start with our first type for megabytes:

public struct Megabytes
{
    public double Value { get; }

    public Megabytes(double value)
    {
        Value = value;
    }

    // Implicitly converts Megabytes to Gigabytes
    public static implicit operator Gigabytes(Megabytes megabytes)
    {
        return new Gigabytes(megabytes.Value / 1024);
    }
}
Enter fullscreen mode Exit fullscreen mode

As you can see in the code example above, we’ll need to consider the next type for gigabytes:

public struct Gigabytes
{
    public double Value { get; }

    public Gigabytes(double value)
    {
        Value = value;
    }

    // Implicitly converts Gigabytes to Megabytes
    public static implicit operator Megabytes(Gigabytes gigabytes)
    {
        return new Megabytes(gigabytes.Value * 1024);
    }
}
Enter fullscreen mode Exit fullscreen mode

These two types are very similar, but they provide logic for converting one way or the other via the static implicit operator. This is what makes the magic happen for us. Now let’s look at how we can use these:

// Implicitly convert Megabytes to Gigabytes
Megabytes storage = new Megabytes(2048); // 2 GB in megabytes
Gigabytes gigabytes = storage; // Implicit conversion to Gigabytes

Console.WriteLine(gigabytes.Value); // Output: 2

// Implicitly convert Gigabytes back to Megabytes
Megabytes megabytes = gigabytes; // Implicit conversion back to Megabytes
Console.WriteLine(megabytes.Value); // Output: 2048
Enter fullscreen mode Exit fullscreen mode

In this code snippet, we can directly assign Gigabytes to Megabytes because of the implicit operator. The underlying value is scaled accordingly, and that way when we go to use either of them we get the correct numeric value backing it!


Wrapping Up How To Automatically Cast Between Types in CSharp

To conclude, being able to automatically cast between types in C# is accomplished by introducing a static implicit operator. In this article, we got to see a simple use case for working with conversions between size of of binary data. If you’d like to see more examples, you can check out:

If you found this useful and you’re looking for more learning opportunities, consider subscribing to my free weekly software engineering newsletter and check out my free videos on YouTube!

Dev Leader Weekly | Substack

My weekly newsletter that simplifies software engineering for you, along with C# code examples. Join thousands of software engineers from companies like Microsoft and Amazon who are already reading! Click to read Dev Leader Weekly, a Substack publication with thousands of subscribers.

favicon weekly.devleader.ca

Want More Dev Leader Content?

  • Follow along on this platform if you haven’t already!
  • Subscribe to my free weekly software engineering and dotnet-focused newsletter. I include exclusive articles and early access to videos: SUBSCRIBE FOR FREE
  • Looking for courses? Check out my offerings: VIEW COURSES
  • E-Books & other resources: VIEW RESOURCES
  • Watch hundreds of full-length videos on my YouTube channel: VISIT CHANNEL
  • Visit my website for hundreds of articles on various software engineering topics (including code snippets): VISIT WEBSITE
  • Check out the repository with many code examples from my articles and videos on GitHub: VIEW REPOSITORY

Top comments (0)