Skip to content
This repository was archived by the owner on Feb 28, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}

}
}