Skip to content

Instantly share code, notes, and snippets.

@akiraveliara
Created March 11, 2022 11:55
Show Gist options
  • Select an option

  • Save akiraveliara/9a28b28763dd775d623e16b04a7b6c24 to your computer and use it in GitHub Desktop.

Select an option

Save akiraveliara/9a28b28763dd775d623e16b04a7b6c24 to your computer and use it in GitHub Desktop.
why do nullable optional params exist
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));
}
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;
}
}
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