Support for Union type?
See original GitHub issueI have a project where we are simulating union types, by having a class where one, and only one, attribute can and must be set.
For instance (contrived example):
public record AgentUnion {
public Monster? Monster {get; set;}
public Player? Player {get; set;}
}
public record Monster {
public int ArtificialIntelligenceLevel {get; set;}
}
public record Player {
public List<string> BackpackContents {get; set;}
}
This allows a heterogenous list of either player or monster.
It would have been great to have an annotation like [OneOf]
or [Union]
that requires the user to provide one, and only one, of those attributes.
And, yes, there is no good way of handling each one of these cases in C#, with a compiler check, and I’m not sure what that would look like.
I’m using:
if (agent.Monster != null){...
} else if (agent.Player != null){...
} else throw new Exception();
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (3 by maintainers)
Top Results From Across the Web
Handbook - Unions and Intersection Types
A union type describes a value that can be one of several types. We use the vertical bar ( | ) to separate...
Read more >PHP 8.0: Union Types
PHP 8.0 comes with support for Union Types! In versions prior to PHP 8.0, you could only declare a single type for properties,...
Read more >Unions and interfaces - Apollo GraphQL Docs
Unions and interfaces are abstract GraphQL types that enable a schema field to return one of multiple object types. Union type.
Read more >Learn TypeScript: Union Types Cheatsheet
Since a variable of a union type can assume one of several different types, you can help TypeScript infer the correct variable type...
Read more >Union Types
For this Flow supports union types. 1function toStringPrimitives(value: ... Each of the members of a union type can be any type, even another...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
In the case of
AnyOf
then the type would be quite straightforward:I’m currently using ServiceStack.OrmLite so I would need that to understand the AnyOf as well.
The
OneOf
has the advantage that it checks for completeness at compile time.@cezarypiatek I have been using OneOf, but I see that
AnyOf
has support for json as well!