Utils/ValidOrNullAttribute.cs

A source generator attribute for properties. When applied, it wraps the property's getter so that if the stored value implements IValid and IsValid is false, the getter returns null (default) instead of the invalid instance.

namespace KOTH;

/// <summary>
/// For properties that contain an <see cref="IValid"/>, wrap the getter to return null if
/// the stored value isn't valid.
/// </summary>
[CodeGenerator(CodeGeneratorFlags.Instance | CodeGeneratorFlags.WrapPropertyGet, "KOTH.ValidOrNullAttribute.OnPropertyGet", 20)]
[AttributeUsage(AttributeTargets.Property)]
public sealed class ValidOrNullAttribute : Attribute
{
	internal static T OnPropertyGet<T>(WrappedPropertyGet<T> p)
	{
		return p.Value is IValid { IsValid: false } ? default : p.Value;
	}
}