TheEdge
TheEdge

Reputation: 9851

How do I pass a list of types to a method call in C#?

I am trying to declare a method where I can pass a list of classes via my parameter aListOfClasses viz:

public static class MyClass
{
  public static void MyCall(List<**WhatDoIPutHere**> aListOfClasses)
  {
    foreach (var item in aListOfClasses)
    {
      var typeInfo = typeof (item);
    }
  }
}

so if I have say a bunch of classes with no common base:

public class ClassOne
{

}

public class ClassTwo
{

}

I want to be able to call my method as followsL

var myListOfClasses = new List<????>();
myListOfClasses.Add(ClassOne);
myListOfClasses.Add(ClassTwo);

MyClass.MyCall(myListOfClasses);

So my questions are:

  1. How do I declare aListOfClasses? What is the type?

Upvotes: 1

Views: 70

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103447

You can declare your method like this:

public static void MyCall(List<Type> aListOfClasses)
{
    foreach (var item in aListOfClasses)
    {
        var typeInfo = item; // no need for typeof again
    }
}

And define your list like:

var myListOfClasses = new List<Type>();
myListOfClasses.Add(typeof(ClassOne));
myListOfClasses.Add(typeof(ClassTwo));

Upvotes: 4

Related Questions