netblognet
netblognet

Reputation: 2016

Generic T in method parameter in C#

I like to do something like this:

public static List<string> ItemsOfEnum(T typeT)
{
    List<string> items = new List<string>();
    foreach (typeT tItem in Enum.GetValues(typeof(typeT)))
       items.Add(tItem);
    return items;
}

How to get the "T" in the parameter-list without changing the return type (List)?

Upvotes: 0

Views: 218

Answers (3)

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

  public static List<string> itemsofenum<typet>()
  { ... }

Upvotes: 0

Lucero
Lucero

Reputation: 60190

Seems to easy... but maybe that's what you were looking for?

public static List<string> ItemsOfEnum<typeT>()
        where typeT: struct, IComparable, IFormattable, IConvertible {
    List<string> items = new List<string>();
    foreach (typeT tItem in Enum.GetValues(typeof(typeT)))
       items.Add(tItem.ToString());
    return items;
}

Note that C# doesn't allow to constrain to enums, so those constraints are more or less the closes you can get.

Upvotes: 6

rekire
rekire

Reputation: 47945

I think you mixed up the Syntax. I guess you want something like this:

public static List<string> ItemsOfEnum<T>(T inputList) {...}

In your for each statement you need to exchange typeT with T. Maybe for your internal list you need to call the toString function to get a string.

Upvotes: 1

Related Questions