0

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?

After_8
  • 189
  • 1
  • 4
  • 16
  • Hi, perhaps use inheritance, https://stackoverflow.com/questions/15574977/wildcard-equivalent-in-c-sharp-generics – IronMan Oct 28 '20 at 21:01
  • thanks for your awnser @IronMan! Could you please explain a bit more specific which approach i should use? I can´t use covariance – After_8 Oct 28 '20 at 21:17
  • maybe have the generic extend a non-generic interface? – IronMan Oct 28 '20 at 21:22
  • this also won´t work. Because i will have to hide `ISomeType GenericProp {get;set,}` with the new keyword like this: `new T GenericProp {get;set,}`. Because of that i will lose the reference to GenericProp if i cast from `IJob` to `IJob` – After_8 Oct 29 '20 at 07:30

0 Answers0