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's In This Article: Automatically Cast Between Types in C#
Remember to check out these platforms:
// FIXME: social media icons coming back soon!
What are Implicit Operators in C#?
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 C#
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);
}
}
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);
}
}
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
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 C#
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. There are plenty of other interesting examples in the repository to check through too!
- This article on a deeper dive for implicit operators.
- This article for using implicit operators on custom multi-type types
- This overview article on implicit operators in C#
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!
Affiliations
These are products & services that I trust, use, and love. I get a kickback if you decide to use my links. There’s no pressure, but I only promote things that I like to use!
- BrandGhost: My social media content and scheduling tool that I use for ALL of my content!
- RackNerd: Cheap VPS hosting options that I love for low-resource usage!
- Contabo: Affordable VPS hosting options!
- ConvertKit: The platform I use for my newsletter!
- SparkLoop: Helps add value to my newsletter!
- Opus Clip: Tool for creating short-form videos!
- Newegg: For all sorts of computer components!
- Bulk Supplements: Huge selection of health supplements!
- Quora: I answer questions when folks request them!
Frequently Asked Questions: Implicit Operators in C#
What are implicit operators in C#?
implicit
keyword and enable implicit type conversion.