I Have the interface IJob
which is an parameter in many of my functions. But this interface is actually generic (IJob<T>
). I want to avoid passing the generic Parameter around to all functions. So i did something like the following:
public interface ISomeType
{
string X { get; set; }
}
public interface IJob<T>
where T : ISomeType
{
string SomeProp { get; set; }
T GenericProp { get; set; }
}
public interface IJob : IJob<ISomeType> { }
public class Job<T> : IJob<T>
where T : ISomeType
{
public string SomeProp { get; set; }
public T GenericProp { get; set; }
}
public class Job : Job<ISomeType> { }
public class SomeOtherType : ISomeType
{
public string X { get; set; }
public string Y { get; set; }
}
So my functions now look like this:
public void DoSomething(IJob job){}
//instead of:
public void DoSomething<T>(IJob<T> job)
where T:ISomeType {}
I Want to do that beacause those functions never touch GenericProp
- they only need to know that T
is ISomeType
Everything works fine, but i came to a point where the following will not work:
I want to store all Jobs in a IDictionary<string,IJob> jobs
and i don´t know the type of GenericProp
before runtime. So i need to cast a Job<T>
to IJob
in order to add it to the Dictionary, but this throws an casting Error.
IJob job = (IJob)new Job<SomeOtherType>();
In general i don´t feel like my solution is a best-practice. But how do I work with polymorphic classes instead?