Generic Type List

I have a generic class and I want to create a list of it. and then at runtime I get the element type

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 achieve

 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 type at run time } 
+8
generics c #
source share
2 answers

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

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

However, if you want to mix jobs of different types (for example, Job<string> and Job<int> ) in the same list, you will have to create a base class or interface that is not shared:

 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 want to get the Job type at runtime, you can do this:

 Type jobType = x[0].GetType(); // Job<string> Type paramType = jobType .GetGenericArguments()[0]; // string 
+20
source share

Having made the interface and implementing it in your class, you can create a list of this type of interface by adding any task:

 interface IJob { //add some functionality if needed } public class Job<T> : IJob { 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; } } List<IJob> x = new List<IJob>(); x.Add(new Job<string>()); 
+1
source share

All Articles