Reputation: 5043
I have a generic class I have created as so:
public abstract class MyClass<T>
{
public T Model
{
get;
protected set;
}
}
And at some point in my code I want to do something with anything of MyClass type. Something like:
private void MyMethod(object param)
{
myClassVar = param as MyClass;
param.Model....etc
}
Is this possible? Or do I need to make MyClass be a subclass of something (MyClassBase) or implement an interface (IMyClass)?
Upvotes: 17
Views: 21303
Reputation: 22448
I believe what you are need is to make MyMethod method generic and add constraint on its type parameter:
interface IMyInterface
{
void Foobar();
}
class MyClass<T>
{
public T Model
{
get;
protected set;
}
}
private void MyMethod<T>(MyClass<T> param) where T : IMyInterface
{
param.Model.Foobar();
}
Upvotes: 16
Reputation: 887453
No.
You need to inherit a non-generic base class or implement a non-generic interface.
Note that you won't be able to use the Model
property, since it cannot have a type (unless you constrain it to a base type and implement an untyped property explicitly).
Upvotes: 6
Reputation: 6883
Yes, you need. If type of generic class is undefined you need to create generic interface or using base-class...
Upvotes: 3