Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Passing a generic list into method and then casting to type

Tags:

c#

list

generics

I have a method that uses a list which I need to pass into it.

Depending on where I call this method the type of the list is different.

Is it possible to pass the list in as a generic list and then cast it to a certain type, or do I need to create parameters for every type of list that can be used (see below)?

public string MyMethod(List<Type1> list1, List<Type2> list2, ...etc )
    {
      switch(someCondition)
        {
          case 1:
           //pass list1 into a method from class1
          break;
          case 2: 
           //pass list2 into a method from class2
         break;

          ...//etc for several more lists
        }
like image 969
Riain McAtamney Avatar asked Mar 29 '11 07:03

Riain McAtamney


2 Answers

Instead of making a single method with multiple parameters, why don't you make several methods with a single List type? It seems you are not sharing much code from one List type to another anyway.

public string MyMethod(List<int> list)
{
  //do something with list
}

public string MyMethod(List<bool> list)
{
  //do something with list1
}
...
like image 74
Fabian Nicollier Avatar answered Sep 27 '22 21:09

Fabian Nicollier


you can create a generic function that accepts generic type like this

public virtual List<T> SelectRecord <T>(int items, IEnumerable<T> list)
    {
        if (items == -1)
            return list.ToList<T>();
        else
            if (items > list.Count<T>())
                return list.ToList<T>();
            else
                return list.Take<T>(items).ToList<T>();
    }

In my example I passed a IEnumerable to my function and it returns a List (where is the type of my object). I don't specify what is the type of the object.

I hope it's helpful.

like image 38
Faber Avatar answered Sep 27 '22 21:09

Faber