0

How can I loop through and get generic class from a list in c#. My code is like this.

private void processList()
{
    List<CommandParameter> parameters = new List<CommandParameter>();
    parameters.Add(new CommandParameter<string>("a", "c", "a"));
    parameters.Add(new CommandParameter<int>("a", "c", 1));

    foreach (var parameter in parameters)
    {
        // How can I loop through the parameters list and get the generic class
    }
}

Is this possible? Can anyone tell me how to solve this?

this is command parameter classes

public class CommandParameter<T> : CommandParameter{
    public string Str { get; private set; }
    public string TypeName { get;private  set; }
    public T TypeValue { get; private set; }

    public CommandParameter(string s, string typeName, T typeValue) {
        Str = s;
        TypeName  = typeName;
        TypeValue = typeValue;
    }
}

public abstract class CommandParameter {

}
10
  • 1
    What exactly do you mean by "and get the generic class"? What do you expect the result to be in the example you've given? What are you trying to achieve? Commented Dec 13, 2015 at 17:25
  • i want to get thecommandParameter<string> and commandParameter<int>from the list in the loop Commented Dec 13, 2015 at 17:29
  • 1
    So just call parameter.GetType(), presumably. Commented Dec 13, 2015 at 17:30
  • Type t = parameter.GetType() right? but then how can i access the fields? do i have to use reflection? Commented Dec 13, 2015 at 17:34
  • 1
    Yes, you would have to. Or use dynamic typing to dynamically perform type inference (calling a generic method). You still haven't explained what you're trying to do, which makes it harder to help you. Commented Dec 13, 2015 at 17:35

1 Answer 1

1

Assuming that you are looking for the generic argument's, here is an example:

List<IEnumerable> coll = new List<IEnumerable>();

coll.Add(new List<string> { "a", "b" });
coll.Add(new List<int> { 7 });

foreach (var item in coll)
{
    var args = item.GetType().GetGenericArguments();
    foreach (var genericArg in args)
    {
        Console.WriteLine(genericArg); // generic types (e.g. string, int)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.