Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method which accepts both int[] and List<int>

Tags:

c#

.net

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 ?

like image 507
now he who must not be named. Avatar asked Nov 19 '14 09:11

now he who must not be named.


3 Answers

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.

like image 123
Tim Schmelter Avatar answered Oct 20 '22 11:10

Tim Schmelter


This might be the right answer:

void TestMethod(IEnumerable<int> list)
like image 3
Yair Nevet Avatar answered Oct 20 '22 10:10

Yair Nevet


Your method could be like this

private void SomeMethod(IEnumerable<int> values)
like image 2
Andrey Korneyev Avatar answered Oct 20 '22 11:10

Andrey Korneyev