Polymorphism
How AutoSDK handles oneOf, anyOf, and allOf schemas with discriminators.
AutoSDK supports OpenAPI's polymorphism constructs (oneOf, anyOf, allOf) and generates idiomatic C# types with proper JSON serialization.
oneOf — Discriminated Unions
OpenAPI oneOf maps to a discriminated union type in C#:
components:
schemas:
Event:
oneOf:
- $ref: '#/components/schemas/MessageEvent'
- $ref: '#/components/schemas/ErrorEvent'
discriminator:
propertyName: type
mapping:
message: '#/components/schemas/MessageEvent'
error: '#/components/schemas/ErrorEvent'Generated C#:
[JsonConverter(typeof(EventJsonConverter))]
public sealed partial class Event
{
public MessageEvent? MessageEvent { get; init; }
public ErrorEvent? ErrorEvent { get; init; }
// Implicit conversions
public static implicit operator Event(MessageEvent value)
=> new() { MessageEvent = value };
// Discriminator-based deserialization
// (auto-generated JsonConverter)
}Computed Discriminators
When specs don't include explicit discriminators, use --compute-discriminators:
autosdk generate spec.json --compute-discriminatorsAutoSDK analyzes the schema structure and infers discriminators from required properties that differ between variants.
anyOf — Flexible Unions
anyOf is similar to oneOf but allows multiple variants to match simultaneously:
Content:
anyOf:
- $ref: '#/components/schemas/TextContent'
- $ref: '#/components/schemas/ImageContent'Generated as a union type where multiple properties can be non-null.
allOf — Composition / Inheritance
allOf merges multiple schemas into a single type:
PetWithOwner:
allOf:
- $ref: '#/components/schemas/Pet'
- type: object
properties:
owner:
$ref: '#/components/schemas/User'Generated as a flat C# class with all properties from both schemas:
public sealed partial class PetWithOwner
{
// From Pet
public string Name { get; set; }
public string Status { get; set; }
// From inline schema
public User? Owner { get; set; }
}JSON Converters
AutoSDK generates custom JsonConverter<T> classes for all polymorphic types. These converters:
- Handle discriminator-based deserialization (for
oneOfwith discriminators) - Try each variant in order (for
oneOf/anyOfwithout discriminators) - Are source-generated (compatible with trimming/NativeAOT)
- Support both serialization and deserialization
Validation
Enable anyOf validation to ensure at least one variant matches:
<AutoSDK_ValidateAnyOfs>true</AutoSDK_ValidateAnyOfs>This generates validation methods that throw if no variant successfully deserializes.
Last updated on