How to Automatically Cast Between Types in C#
Tags: coding, programming, dotnet, csharp
Published: 2024-03-18 16:00:00

The post [How to Automatically Cast Between Types in C#](https://www.devleader.ca/2024/03/11/how-to-automatically-cast-between-types-in-c/) appeared first on [Dev Leader](https://www.devleader.ca).

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 operator`s. 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:

```csharp
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);
    }
}
```

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

```csharp
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);
    }
}
```

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:

```csharp
// 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
```

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:

* This [project on my DevLeader GitHub](https://github.com/ncosentino/DevLeader/tree/master/OperatorExamples/OperatorExamples.ImplicitOperators). There are plenty of other interesting examples in the repository to check through too!
    
* [This article on a deeper dive for implicit operators](https://www.devleader.ca/2024/03/04/implicit-operators-in-c-how-to-simplify-type-conversions/).
    
* [This article for using implicit operators on custom multi-type types](https://www.devleader.ca/2023/05/31/implicit-operators-in-c-and-how-to-create-a-multi-type/)
    
* [This overview article on implicit operators in C#](https://www.devleader.ca/2023/08/04/implicit-operators-clean-code-secrets-or-buggy-nightmare/)
    

If you found this useful and you’re looking for more learning opportunities, consider [subscribing to my free weekly software engineering newsletter](https://subscribe.devleader.ca) and check out my [free videos on YouTube](https://www.youtube.com/@devleader?sub_confirmation=1)!

{% embed https://weekly.devleader.ca/embed %}

---

## **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**](https://subscribe.devleader.ca/)    
* Looking for courses? Check out my offerings:  
    [**VIEW COURSES**](https://devleader.ca/courses)    
* E-Books & other resources:  
    [**VIEW RESOURCES**](https://products.devleader.ca/)    
* Watch hundreds of full-length videos on my YouTube channel:  
    [**VISIT CHANNEL**](https://youtube.com/@devleader?sub_confirmation=1)    
* Visit my website for hundreds of articles on various software engineering topics (including code snippets):  
    [**VISIT WEBSITE**](https://devleader.ca/)    
* Check out the repository with many code examples from my articles and videos on GitHub:  
    [**VIEW REPOSITORY**](https://github.com/ncosentino/DevLeader)