C# continues to evolve with features that help developers write cleaner, safer, and more maintainable code. One of the interesting additions in C# 15 is Union Types.
Before C# 15, developers often used object , interfaces, abstract classes, or custom wrapper classes when a method needed to represent multiple possible types.
These approaches worked, but they had limitations. For example, using object. allows almost any type, while interfaces and abstract classes require a shared inheritance relationship.
C# 15 Union Types solve this problem by allowing you to define a fixed set of permitted types.
In this tutorial, we will explore what Union Types are, how they work, their syntax, practical examples, and when to use them in real-world applications.
1. What Are Union Types in C# 15?
A Union Type represents a value that can be exactly one of several predefined types.
In simple terms, instead of creating a variable that can contain anything, you can define a variable that accepts only specific types.
For example, imagine an application that manages different types of pets:
- Cat
- Dog
- Bird
Traditionally, you might use an interface or object to represent all three types.
With C# 15, you can define a union directly:
public record class Cat(string Name); public record class Dog(string Name); public record class Bird(string Name); public union Pet(Cat, Dog, Bird);
Here, Pet is a Union Type that can contain:
- A Cat object
- A Dog object
- A Bird object
It cannot contain an unrelated type such as string or int.
This makes the allowed types explicit and gives the compiler more information about your code.
2. How to Declare a Union Type
C# 15 introduces the union keyword to declare a Union Type.
Syntax:
public union UnionName(Type1, Type2, Type3);
Let's understand it with another example:
public record class EmailNotification(string Email);
public record class SmsNotification(string Phone);
public record class PushNotification(string DeviceId);
public union Notification(
EmailNotification,
SmsNotification,
PushNotification
);
In this example, the Notification union supports three notification types.
You can assign any of these types directly:
Notification notification =
new EmailNotification("user@example.com");
Notification notification2 =
new SmsNotification("9876543210");
Notification notification3 =
new PushNotification("DEVICE-101");
Notice that you don't need to explicitly create a Notification object for each type.
C# provides implicit conversions from the declared case types to the union type.
3. Union Types vs Object in C#
Before C# 15, developers commonly used object to store different types of values.
Consider this example:
object data = "Hello C#"; data = 100; data = DateTime.Now;
The problem is that object accepts almost any type.
The compiler cannot guarantee that the value belongs to a specific set of permitted types.
Now consider Union Types:
public union ApiResponse(
string,
int,
bool
);
You can assign only the declared case types.
ApiResponse response = "Success"; response = 200; response = true;
An unrelated type such as DateTime isn't an allowed case.
Union Types provide a more explicit contract when you know exactly which types are allowed.
4. Pattern Matching with Union Types
One of the most powerful benefits of Union Types is exhaustive pattern matching.
The compiler knows all the possible case types and can verify that your switch expression handles them.
Let's understand with an example.
public record class Cat(string Name); public record class Dog(string Name); public record class Bird(string Name); public union Pet(Cat, Dog, Bird);
Now create a method to identify the pet:
Pet pet = new Dog("Rocky");
string result = pet switch
{
Cat c => $"Cat Name: {c.Name}",
Dog d => $"Dog Name: {d.Name}",
Bird b => $"Bird Name: {b.Name}"
};
Console.WriteLine(result);
Output:
Dog Name: Rocky
Notice something important.
We haven't added a default ( _ ) condition.
Why?
Because the compiler already knows the complete set of possible types:
- Cat
- Dog
- Bird
When all cases are handled, the switch expression is exhaustive.
If you add another case type to the union, the compiler can identify switch expressions that need updating.
This makes your application easier to maintain as requirements change.
5. Real-World Example: Result or Error Handling
One of the most useful applications of Union Types is handling success and error responses.
Imagine an API method that searches for a product.
The method can produce two possible outcomes:
- Product found.
- Product not found.
Traditionally, developers might return null, throw an exception, or use a custom response class.
With Union Types, you can explicitly define both outcomes.
Step 1: Create the response types
public sealed record Product(
int Id,
string Name
);
public sealed record ProductNotFound(
int Id
);
Step 2: Define the Union Type
public union ProductLookup(
Product,
ProductNotFound
);
Step 3: Create a method
public ProductLookup GetProduct(int id)
{
if (id == 1)
{
return new Product(
1,
"Laptop"
);
}
return new ProductNotFound(id);
}
Step 4: Handle the result
ProductLookup result = GetProduct(1);
string message = result switch
{
Product p => $"Product Found: {p.Name}",
ProductNotFound e =>
$"Product with ID {e.Id} not found."
};
Console.WriteLine(message);
Output:
Product Found: Laptop
This approach makes the possible outcomes clear and forces callers to consider each declared case.
6. Union Types for Single Values or Collections
Another interesting use case is accepting either a single value or a collection of values.
For example, imagine a method that accepts either one tag or multiple tags.
You can define a generic Union Type:
public union OneOrMore<T>(
T,
IEnumerable<T>
)
{
public IEnumerable<T> AsEnumerable() =>
Value switch
{
T single => [single],
IEnumerable<T> multiple => multiple,
null => []
};
}
Now you can pass a single value:
OneOrMore<string> tags = "CSharp";
Or multiple values:
OneOrMore<string> tags =
new[] { "CSharp", "DotNet", "WebAPI" };
Both can be converted into an enumerable collection:
foreach (var tag in tags.AsEnumerable())
{
Console.WriteLine(tag);
}
This is useful when designing flexible APIs that accept either individual values or collections.
7. How Union Types Improve Type Safety
Type safety is one of the major reasons developers should understand Union Types.
Consider a traditional method:
public object GetResponse()
{
return "Success";
}
The return type doesn't tell the caller what kind of value to expect.
The caller must inspect the returned object and handle unexpected types.
With Union Types:
public union ApiResult(
SuccessResponse,
ErrorResponse
);
Now the method explicitly communicates its possible outcomes.
The compiler can also verify that the caller handles every declared case.
Benefits include:
- Stronger type contracts.
- Fewer unexpected type scenarios.
- Better pattern matching.
- More maintainable API designs.
- Clearer method return types.
- Compile-time exhaustiveness checking.
8. Union Types vs Interfaces vs Abstract Classes
Developers have traditionally used interfaces and abstract classes to represent related types.
However, Union Types offer a different approach.
1. Union Types (C# 15)
- Represents one value from a predefined set of types.
- Uses the
unionkeyword. - Does not require types to share a common base class or interface.
- Supports implicit conversions from declared case types.
- Provides compiler-checked exhaustive pattern matching.
- Best for handling multiple possible outcomes, such as Success/Error or different notification types.
2. Interfaces
- Defines a contract that classes and structs can implement.
- Supports multiple interface implementations.
- Can define method signatures, properties, and default implementations.
- Allows unrelated classes to share common behavior.
- Does not restrict implementations to a fixed set of types.
- Best for dependency injection, abstraction, and loosely coupled architecture.
3. Abstract Classes
- Provides a common base class for related derived classes.
- Can contain abstract and implemented methods.
- Supports constructors, fields, and properties.
- Allows shared business logic across derived classes.
- A class can inherit from only one base class.
- Best when related classes need shared state and implementation.
9. Important Things to Know About Union Types
Before using Union Types in production applications, understand these points:
- A union represents one of its declared case types, not multiple cases simultaneously.
- Case types do not need to share an inheritance relationship.
- C# provides implicit conversions from case types to the union.
- Switch expressions can be checked for exhaustive case coverage.
- Union Types are useful for modeling success/error results and message types.
- The compiler also supports enhanced nullability analysis for unions.
- The default value of a union struct has a null underlying value, so consider null handling where appropriate.
One implementation detail is worth knowing: the built-in union declaration generates a struct that stores its underlying value through an object? property. Value types can therefore involve boxing. For performance-sensitive scenarios, custom union implementations can use the supported non-boxing access pattern.
Conclusion
C# 15 Union Types are an important improvement to the C# type system.
They allow developers to define a fixed set of possible types without requiring those types to share a common interface or base class.
The combination of implicit conversions, pattern matching, and exhaustive switch checking makes Union Types particularly useful for API response handling, error management, notification systems, and flexible method contracts.
If you are working with ASP.NET Core Web API, MVC, or modern .NET applications, understanding Union Types can help you design clearer and safer application architectures.
Keep learning. Keep coding. Keep exploring modern C#!
— Kaushal Rao