Skip to content
This repository has been archived by the owner on Feb 28, 2024. It is now read-only.

Commit

Permalink
Merge pull request #79 from neos-modding-group/nullable-config
Browse files Browse the repository at this point in the history
Fix Nullable<T> configs
  • Loading branch information
zkxs authored Oct 1, 2022
2 parents 1be565c + 958cc6e commit 0b3bea3
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 5 deletions.
3 changes: 1 addition & 2 deletions NeosModLoader/ModConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -363,8 +363,7 @@ public void Set(ModConfigurationKey key, object? value, string? eventLabel = nul

if (value == null)
{
bool cannotBeNull = definingKey!.ValueType().IsValueType && Nullable.GetUnderlyingType(definingKey!.ValueType()) == null;
if (cannotBeNull)
if (Util.CannotBeNull(definingKey!.ValueType()))
{
throw new ArgumentException($"null cannot be assigned to {definingKey.ValueType()}");
}
Expand Down
20 changes: 17 additions & 3 deletions NeosModLoader/ModConfigurationKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,13 +136,27 @@ public ModConfigurationKey(string name, string? description = null, Func<T>? com
/// <returns>true if the value is valid</returns>
public override bool Validate(object? value)
{
// specifically allow nulls for class types
if (value is T || (value is null && !typeof(T).IsValueType))
if (value is T typedValue)
{
return ValidateTyped((T?)value);
// value is of the correct type
return ValidateTyped(typedValue);
}
else if (value == null)
{
if (Util.CanBeNull(ValueType()))
{
// null is valid for T
return ValidateTyped((T?)value);
}
else
{
// null is not valid for T
return false;
}
}
else
{
// value is of the wrong type
return false;
}
}
Expand Down
12 changes: 12 additions & 0 deletions NeosModLoader/Util.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,5 +90,17 @@ internal static HashSet<T> ToHashSet<T>(this IEnumerable<T> source, IEqualityCom
return new HashSet<T>(source, comparer);
}

// check if a type cannot possibly have null assigned
internal static bool CannotBeNull(Type t)
{
return t.IsValueType && Nullable.GetUnderlyingType(t) == null;
}

// check if a type is allowed to have null assigned
internal static bool CanBeNull(Type t)
{
return !CannotBeNull(t);
}

}
}

0 comments on commit 0b3bea3

Please sign in to comment.