Skip to content

Instantly share code, notes, and snippets.

@edihasaj
Created January 9, 2022 19:28
Show Gist options
  • Save edihasaj/95343786a23f338ffedcd44ae8592a13 to your computer and use it in GitHub Desktop.
Save edihasaj/95343786a23f338ffedcd44ae8592a13 to your computer and use it in GitHub Desktop.
C# list not null or empty collection validation attribute
public class NotNullOrEmptyCollectionAttribute : ValidationAttribute
{
private readonly int _length;
public NotNullOrEmptyCollectionAttribute(int length)
{
_length = length;
}
public NotNullOrEmptyCollectionAttribute()
{
_length = -1;
}
public override bool IsValid(object value)
{
return value switch
{
ICollection collection when _length > -1 => collection.Count >= _length,
ICollection collection => collection.Count != 0,
_ => value is IEnumerable enumerable && enumerable.GetEnumerator().MoveNext()
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment