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?

+6
source share
5 answers

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.

+7
source

This may be the correct answer:

 void TestMethod(IEnumerable<int> list) 
+3
source

Your method might be like this

 private void SomeMethod(IEnumerable<int> values) 
+2
source

you can try this

  private void TestMethod(dynamic param) { // Console.Write(param); foreach (var item in param) { Console.Write(item); } } TestMethod(new int[] { 1, 2, 3 }); TestMethod(new List<string>() { "x","y","y"}); 
+1
source

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.

+1
source

Source: https://habr.com/ru/post/978381/


All Articles