1

I'm attempting to create a custom required validation attribute which will be able to take in a 1d array of any size and verify that at least one element is not null/empty string. I'm having some trouble figuring out how to turn the incoming generic object into an array. Here's what I have so far:

public class RequiredArrayAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        var valueType = value.GetType();

        if (!valueType.IsArray)
        {
            return false;
        }

        bool hasValue = false;

        foreach (var item in value)
        {
            /* if (item != null/empty)
             * {
             *    hasValue = true;
             * }
            */
        }

        return hasValue;
    }
}

While my specific use case in this instance will be dealing with string[], I'd like to keep the attribute as generic as possible for future use in other projects. Any ideas on how to proceed?

EDIT:

I basically need to do something like:

foreach (var item in (valueType[])value)
{
    // ...
}

But I'm not sure how/if it's possible to dynamically cast to an array like that.

3
  • What version of C# are you using? Can you use Linq and generics? ie. if you had a generic collection you could do something like .Where(x => x != null).Count() > 0 - of course that handles the null part rather than the empty string part :) Commented Aug 24, 2011 at 4:33
  • I'm using C# 4, so I have both LINQ and generics. I can represent my model data as a List<string> without a problem. However, the main problem still remains - how would I cast object value as a List<T>? Commented Aug 24, 2011 at 13:11
  • Does this help - something like the below - Assuming the object implements IList as opposed to IEnumerable: IList collection = (IList)myObject; Commented Aug 25, 2011 at 0:34

1 Answer 1

0

i believe you need following: generic handeling of your loop: check answer below

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

Cast as T:

you can create separate class that will represent T

eg: public class Foo{ public string Boo{get;set;} }

and after you put it into List list = new List() etc:)

Sign up to request clarification or add additional context in comments.

1 Comment

See my comment to Jen on my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.