Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of generic Type

Tags:

c#

generics

I have a generic class and I want to create a list of it. and then at run time I get the type of the item

Class

public class Job<T>
{
    public int ID { get; set; }
    public Task<T> Task { get; set; }
    public TimeSpan Interval { get; set; }
    public bool Repeat { get; set; }
    public DateTimeOffset NextExecutionTime { get; set; }

    public Job<T> RunOnceAt(DateTimeOffset executionTime)
    {
        NextExecutionTime = executionTime;
        Repeat = false;
        return this;
    }
}

What I want to achive

List<Job<T>> x = new List<Job<T>>();

public void Example()
{
    //Adding a job
    x.Add(new Job<string>());

    //The i want to retreive a job from the list and get it's type at run time
}
like image 916
Erric J Manderin Avatar asked Jul 30 '13 22:07

Erric J Manderin


People also ask

Is ArrayList generic type?

Both ArrayList and vector are generic types.

Is any a generic type?

Definition: “A generic type is a generic class or interface that is parameterized over types.” Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.


1 Answers

If all of your jobs are of same type (e.g. Job<string>) you can simply create a list of that type:

List<Job<string>> x = new List<Job<string>>();
x.Add(new Job<string>());

However, if you want to mix jobs of different types (e.g. Job<string> and Job<int>) in the same list, you'll have to create a non-generic base class or interface:

public abstract class Job 
{
    // add whatever common, non-generic members you need here
}

public class Job<T> : Job 
{
    // add generic members here
}

And then you can do:

List<Job> x = new List<Job>();
x.Add(new Job<string>());

If you wanted to get the type of a Job at run-time you can do this:

Type jobType = x[0].GetType();                       // Job<string>
Type paramType = jobType .GetGenericArguments()[0];  // string
like image 90
p.s.w.g Avatar answered Oct 25 '22 22:10

p.s.w.g