Question: Write a single method declaration which can accept both List<int>
and int[]
My answer involved something like this:
void TestMethod(object param) // as object is the base class which can accept both int[] and List<int>
But that was not the intended answer, she said so.
Any ideas how that method signature would be ?
You can use IList<int>
which both, int[]
and List<int>
implement:
void TestMethod(IList<int> ints)
On that way you can still use the indexer or the Count
property( yes, an array has a Count
property if you cast it to IList<T>
or ICollection<T>
). It's the greatest possible intersection between both types which allows fast access, using for
-loops or other supported methods.
Note that some methods are not supported even if they can be called like Add
, you'll get a NotSuportedException
at runtime("Collection was of a fixed size") if you use it with an array.
This might be the right answer:
void TestMethod(IEnumerable<int> list)
Your method could be like this
private void SomeMethod(IEnumerable<int> values)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With