C # Equivalent to Java GenericType <?>
I work with some generics in C #. I have an abstract generic class:
public abstract class BaseClass<T> where T : Foo { } and the type parameter is specified when other classes inherit from the base class.
I am also trying to write code for another abstract class that should store one of these base classes, but it will not know the base class parameter (and it does not need to know). In Java, I could just write:
protected BaseClass<?> myBaseClass; But in C #, he insists that I give him a type parameter. If I declare it as:
protected BaseClass<Foo> myBaseClass; I cannot assign parameterized BaseClass values ββto BaseClass .
Is there any work to achieve the BaseClass<?> Effect in C #? Obviously, there are ways to restructure my code to avoid the need, for example, parameterizing all classes that use BaseClass , but that would be less than ideal. Any help would be appreciated!
To map Java behavior in C #, an additional non-generic interface is usually added to the inheritance hierarchy.
public interface IBaseClass { Foo GetValue(); void SetValue(Foo value); } public abstract class BaseClass<T> : IBaseClass where T : Foo { public T GetValue<T>() { /* ... */ } public void SetValue<T>(T value) { /* ... */ } Foo IBaseClass.GetValue() // Explicit interface method implementation { return (Foo)GetValue<T>(); } void IBaseClass.SetValue(Foo value) // Explicit interface method impl. { SetValue<T>((T)value); } } And then use IBaseClass where you need BaseClass<?> :
IBaseClass myClass; Foo f = myClass.GetValue();