A method that accepts both int [] and List <int>
Question: Write a single method declaration that can accept either List<int>
or int[]
My answer was 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 on how this method signature will be?
You can use IList<int>
, which are implemented both by int[]
and List<int>
:
void TestMethod(IList<int> ints)
In this case, you can still use the indexer or Count
property (yes, the array has the Count
property if you added it to IList<T>
or ICollection<T>
). This is the maximum possible intersection between both types that provides quick access using for
-loops methods or other supported methods .
Note that some methods are not supported, even if they can be called as Add
, you will get a NotSuportedException
at runtime ("The collection has a fixed size") if you use it with an array.
How about using Generics:
public static void TestMethod<T>(IEnumerable<T> collection) { foreach(var item in collection) { Console.WriteLine(item); } }
and use it as follows:
int[] intArray = {1,2}; List<int> intList = new List<int>() { 1,2,3}; int[] intArray = {1,2}; List<int> intList = new List<int>() { 1,2,3}; TestMethod(intArray); TestMethod(intList); string[] stringArray = { "a","b","c"} List<string> stringList = new List<string>() { "x","y","y"}; TestMethod(stringArray); TestMethod(stringList);
Now you can pass any type.