C
C#4mo ago
13eck

Hope to declare class member with variable type

I’m making a simple dice rolling Discord app and I’m having issues creating classes for some of the data types as they have variable type members. Specifically, the Application command interaction data option has a value field that can be a string, integer, double, or boolean. How do I accommodate this in a class? I’m honestly thinking of just reading from a JsonDocument and not worrying about it, but that can’t be a good idea, long-term, right?
6 Replies
Pobiega
Pobiega4mo ago
Without a discriminator (a special value on the object that indicates what "variant" of the object it is) this is... non trivial.
13eck
13eckOP4mo ago
That’s what I was afraid of. Will discriminated unions (coming soon™️) help out?
Pobiega
Pobiega4mo ago
Your best bet is probably to look how other discord libraries handle it. My go-to is Remora, which does this You'll also need to look at (or use) the Remora.Rest.Json package that does the actual handling of the values, specifically the DataObjectConverter<TInterface, TImplementation> class Regarding DUs, maybe - depends on how System.Text.Json will support it Stuff like that is still very much an unknown, and without library support it won't work at all, but once DUs are finalized its very likely that STJ will support them Actually, if I'm not mistaken the type property on that json object can be used as a type descriminator hm, or maybe not.. dunno. it does have STRING, BOOLEAN, INTEGER, NUMBER types, but also some others if its always true that any given value of type only has a single possible type of value, this is much easier to do with just normal STJ + interface + [JsonPolymorphic] + [JsonDerivedType]
wasabi
wasabi4mo ago
I'd just make it an object. And then stick a custom JSON converter on it that can determine what it is.
Pobiega
Pobiega4mo ago
I looked closer at how Remora does it out of curiosity, this is the "key": https://github.com/Remora/Remora.Rest/blob/main/Remora.Rest/Json/OneOfConverter.cs so given this, it tests all of the OneOf arguments in a certain order (numbers, then collections, then built in types) and the first matching type that successfully deserializes is what is will be returned I think its a very good solution, if you are fine with using OneOf.
13eck
13eckOP4mo ago
I’ll have a look, thanks
Want results from more Discord servers?
Add your server