I'm still new to C# and cannot wrap my head around this issue.
I have a two classes deriving from a generic class with T deriving from BackgroundWorker (see below). How can I have a field in another class that is able to hold either of the two derived classes and access the field with the derived BackgroundWorker? I need to be able to subscribe to the derived BackgroundWorker's events and issue e.g. CancelAsync command...
I have a generic class:
public class GenericClass<T> where T : BackgroundWorker
{
public T BgWorker;
}
and derive two classes from it:
public class DerivedOne : GenericClass<BackgroundWorkerOne>
{ }
public class DerivedTwo : GenericClass<BackgroundWorkerTwo>
{ }
where:
public class BackgroundWorkerOne : BackgroundWorker
{ }
public class BackgroundWorkerOne : BackgroundWorker
{ }
However, how can I make a field/property in another class that is able to hold either DerivedOne or DerivedTwo depending on some other variable?
I have tried
public class AnotherClass
{
public GenericClass<BackgroundWorker> Derived;
public void DoSomething()
{
Derived = new DerivedOne();
}
}
But I get the "Cannot implicitly convert type 'DerivedOne' to 'GenericClass<BackgroundWorker>'" error. Casting it
Derived = (GenericClass<BackgroundWorker>)new DerivedOne();
does not work either.
As mentioned, I would like to subscribe to the events in Derived.BgWorker
regardless if the Derived
is of type DerivedOne
or DerivedTwo
.
Is using generics here the best option? Or would another path (interface, shadowing or something else entirely) be a better solution?
Any help would be appreciated!
EDIT
I see that my approach, as has been pointed out in Cast Generic<Derived> to Generic<Base>, is not really feasible. Thank you for that clarification. The code I've shown above is only what I have tried so far, not necesarrily a fixed direction in which the code has to develop.
Furthermore, my question was more geared towards finding a way to access the BackgroundWorker (property with varying types in different classes) from the same base class.
What would be a suitable alternative to be able to access the BackgroundWorker (wheather BackroundWorkerOne
or BackgroundWorkerTwo
) property of the Derived
property? Is there a possiblity to do so or should I rethink my concept?