0

The method I am overriding has the following signature.

public override bool IsValid(object value)

The object that is passed in is a List but the the list type is unknown. It could be List<string> or List<int>.

I need to cast this into a List<object>. I've tried

if (!(value is IList temp))
{
    return false;
}

List<object> list = temp.OfType<object>().ToList();

which sort of works, but it filters out any null values, presumably because they are not OfType<object>

So what's the best way of doing this?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Steve Wright
  • 534
  • 1
  • 4
  • 14

2 Answers2

0

temp.OfType().ToList();

OfType checks if the element is of the required type, and if so it puts it in a new temporary list.

What you're asking is simply a cast, since every instance in C# is an object: (List<object>)temp. Edit: apparently covariance doesn't work here.

There's absolutely no reason to do this though, you can simply enumerate it as it is: foreach(var obj in (IList)temp). All collections implement the IList non-generic interface.

Blindy
  • 65,249
  • 10
  • 91
  • 131
  • That's a working solution. I also needed to use the .All() method which List provides, but IList doesn't. So @ZoharPeled suggestion of temp.Cast().ToList() is actually better for me – Steve Wright Jun 24 '20 at 10:11
  • `IList` doesn't provide `All`, but Linq does, and that works on every `IEnumberable` or `IEnumerable`. Cast it accordingly if that's what you need! – Blindy Jun 25 '20 at 14:22
0

If the input is either List<int> or List<string> and nothing else, then I think the best approach is to check specifically for these types. So something like:

List<object> list ;
if (value is List<int> listOfInts) 
{
   list = listOfInts.Cast<object>().ToList();
} 
else if (value is List<string> listOfStrings) 
{
   list = listOfStrings.Cast<object>().ToList();
} 
else 
{
   throw new ArgumentException(...);
}

This might seem redundant, but it might save you a lot of headache down the line, since you will catch if someone passes a List<SomethingElse> or even a List<object> which would be illegal according to your specification.

JacquesB
  • 41,662
  • 13
  • 71
  • 86
  • Unfortunately the list type is unknown. List and List were just two examples of what he list could be. This is being used in a custom validation attribute. That attribute could be applied to a List – Steve Wright Jun 24 '20 at 10:13