Created
March 11, 2022 11:55
-
-
Save akiraveliara/9a28b28763dd775d623e16b04a7b6c24 to your computer and use it in GitHub Desktop.
why do nullable optional params exist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| JsonObject payloadObject = new(); | |
| if(payload.Nickname.Value == null && payload.Nickname.TreatAsNull == true) | |
| { | |
| payloadObject.Add("nick", JsonValue.Create<String>(null)); | |
| } | |
| else if(payload.Nickname.Value != null) | |
| { | |
| payloadObject.Add("nick", JsonValue.Create(payload.Nickname.Value)); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| /// <summary> | |
| /// Represents an optional parameter; ie a parameter which may or may not be sent to Discord. | |
| /// Normally this problem is handled using <c>[JsonIgnore(Condition = JsonIgnoreCondition.IgnoreWhenNull)]</c>, | |
| /// but this is unfortunately not always possible. | |
| /// </summary> | |
| /// <typeparam name="TParam">Any nullable parameter type.</typeparam> | |
| public struct OptionalParameter<TParam> | |
| { | |
| /// <summary> | |
| /// The "real", underlying value of this instance. | |
| /// </summary> | |
| public TParam? Value { get; set; } | |
| public static implicit operator TParam?(OptionalParameter<TParam> parameter) | |
| => parameter.Value; | |
| public static implicit operator OptionalParameter<TParam>(TParam? value) | |
| => new() { Value = value, TreatAsNull = false }; | |
| /// <summary> | |
| /// Whether this should be sent to Discord: if this is true, we send a <c>null</c> value to Discord, if not, we ignore a null value. | |
| /// </summary> | |
| public Boolean TreatAsNull { get; set; } | |
| public OptionalParameter(TParam? value, Boolean treatAsNull = false) | |
| { | |
| this.Value = value; | |
| this.TreatAsNull = treatAsNull; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public record ModifyGuildMemberRequestPayload | |
| { | |
| /// <summary> | |
| /// The nickname to force the user to assume. | |
| /// </summary> | |
| public OptionalParameter<String?> Nickname { get; init; } | |
| // ... | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment