The MultiType.NET.Generator package enables you to define your own custom union types using a simple [GenerateAny] attribute. It removes boilerplate and auto-generates rich union logic for your own domain-specific types.
- Generates a struct based on your type definition.
- Implements all core APIs:
Match,TryMatch,Map,Switch,From,TryFrom, and more. - Adds optional
System.Text.Jsonsupport for serialization. - Integrates seamlessly with Controllers, Minimal APIs, and DTOs.
dotnet add package MultiType.NET.Generator[GenerateAny(typeof(int), typeof(string))]
public partial struct IntOrString;IntOrString value = "hello";
var result = value.Match(
i => $"Int: {i}",
s => $"String: {s}"
);[GenerateAny(typeof(Success), typeof(Warning), typeof(Error), typeof(Info))]
public partial struct StatusType
{
public static StatusType From(string value) => value.ToLowerInvariant() switch
{
"success" => new Success(),
"warning" => new Warning(),
"error" => new Error(),
"info" => new Info(),
_ => throw new ArgumentException("Invalid status")
};
public bool IsSuccess => this.Is<Success>();
public bool IsWarning => this.Is<Warning>();
public bool IsError => this.Is<Error>();
public bool IsInfo => this.Is<Info>();
public readonly struct Success { }
public readonly struct Warning { }
public readonly struct Error { }
public readonly struct Info { }
}The generated type is automatically decorated to support System.Text.Json Without any manual changes.
// Generates a discriminated union of int, string, or Guid
[GenerateAny(typeof(int), typeof(string), typeof(Guid))]
public partial struct Payload;// POST endpoint accepting Payload from body
[HttpPost("submit-payload")]
public async Task<IActionResult> SubmitPayload(
[FromBody] Payload payload)
{
// payload.Match(...)
return Ok();
}
// GET endpoint accepting Payload from query
[HttpGet("search")]
public async Task<IActionResult> SearchPayload(
[FromQuery] Payload query)
{
return Ok();
}| Use Case | Example |
|---|---|
| API Payloads | IntOrString for flexible IDs |
| Workflow Status | StatusType for state modeling |
| Dynamic Input | StringOrBoolOrInt from forms or query strings |
- Generated files are
.g.csand automatically included during compilation. - Works with source generators (no runtime reflection).
- Types must be
readonly struct.
➡️ Proceed to CLI Generator for generating Any<T1..T50> and custom JSON converters.