Reputation: 2614
I'm writting generic validate function. It will use reflection to navigate through properties of an object and validate them. But I got a problem with collection property. I can determine if it's an array
or generic
but can not cast it in order to loop throught its entities.
private static bool Validate(object model)
{
if (model.GetType().IsGenericType || model.GetType().IsArray)
{
//I want to convert model to IEnumerable here in order to loop throught it
//It seems that .NET 2.0 doesn't allow me to cast by using
IEnumerable lst = model as IEnumerable;
//or
IEnumerable lst = (IEnumerable) model;
}
}
UPDATE:
Silly me, turned out that using
IEnumerable lst = model as IEnumerable;
work perfectly. The problem I got is that by switching from .NET 4.0 to .NET 2.0, I stuck in a conclusion that .NET 2.0 doesn't support direct cast to IEnumerable
without provide a specific type and I haven't noticed that System.Collection
hasn't been imported. I feel like an idiot now.
P/S: sorry you guys for the waste of time
Upvotes: 2
Views: 719
Reputation: 23113
IEnumerable lst = model as IEnumerable;
if(lst != null)
{
//loop
}
This should work if the model implements IEnumerable
.
The following would throw an invalid cast exception:
IEnumerable lst = (IEnumerable) model;
Upvotes: 2