Created
January 9, 2022 19:28
-
-
Save edihasaj/95343786a23f338ffedcd44ae8592a13 to your computer and use it in GitHub Desktop.
C# list not null or empty collection validation attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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