Q:

object as List always return null

I wanted to ensure the list property of my model is not empty,so i created a ValidationAttribute, but the value as List< long > always return null even if the property decorated with NoEmpty is of type List< long >.
why? and how to do it properly?
public class NoEmptyAttribute: ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var list = value as List<long>;

        var msg = $"{validationContext.MemberName} can not bt empty";

        if (list == null) return new ValidationResult(msg);

        return list.Count == 0 ? new ValidationResult(msg) : ValidationResult.Success; 
    }
}

I updated my code,and now it works fine:
public class NoEmptyAttribute: ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var list = value as IEnumerable;

        var msg = $"{validationContext.MemberName} can not be null";

        if (list == null) return new ValidationResult(msg);

        return list.Cast<object>().Any() ? ValidationResult.Success : new ValidationResult(msg);
    }
}

The reason of why value as List< long > always return null is that the value is of type HashSet< long >.

A:

I wrote a unit test (based on the code of your NoEmptyAttribute) and everything work as expected
[TestClass()]
public class NoEmptyAttributeTests
{
    [TestMethod]
    public void GetValidationResult_ListLongWithElements_ReturnsNull()
    {
        object obj = new object();
        object value = new List<long> { 1, 2 };

        ValidationContext ctx = new ValidationContext( obj ) { MemberName = "Foo" };
        var noempty = new NoEmptyAttribute();
        var result = noempty.GetValidationResult( value, ctx );
        Assert.IsNull( result );
    }

    [TestMethod]
    public void GetValidationResult_ListLongEmpty_ReturnsCannotBeEmpty()
    {
        object obj = new object();
        object value = new List<long>();

        ValidationContext ctx = new ValidationContext( obj ) { MemberName = "Foo" };
        var noempty = new NoEmptyAttribute();
        var result = noempty.GetValidationResult( value, ctx );
        Assert.IsNotNull( result );
        Assert.AreEqual( "Foo can not bt empty", result.ErrorMessage );
    }

    [TestMethod]
    public void GetValidationResult_ListLongNull_ReturnsCannotBeEmpty()
    {
        object obj = new object();
        object value = null;

        ValidationContext ctx = new ValidationContext( obj ) { MemberName = "Foo" };
        var noempty = new NoEmptyAttribute();
        var result = noempty.GetValidationResult( value, ctx );
        Assert.IsNotNull( result );
        Assert.AreEqual( "Foo can not bt empty", result.ErrorMessage );
    }
}

