Reputation: 35
I have two classes in C#:
public abstract class BaseAccount
{
public void MyMethod1()
{
//Code
}
}
public class DerivedAccount : BaseAccount
{
public void MyMethod2()
{
//code
}
}
public class AccountBL<T> where T : BaseAccount, new()
{
public void TestMethod()
{
T obj1 = new T();
obj1.MyMethod1();
obj1.MyMethod2(); //Wrong!!! Can I use a method in derived class without changing constaint??
}
}
How can I use public properties of a derived class in the generic class?
I don't want implement several generic class for each of my Derived Class.
Upvotes: 0
Views: 127
Reputation: 1
It is because your Structure. With where T : BaseAccount, new()
your're saying that T has to inherit from BaseAccount
so you can use the methods from BaseAccount
. If you want to use the Methods from DerivedAccount
you have to check this first.
Upvotes: 0
Reputation: 3499
It is because your Structure. With where T : BaseAccount, new()
your're saying that T has to inherit from BaseAccount
so you can use the methods from BaseAccount
. If you want to use the Methods from DerivedAccount
you have to check this first:
if (obj1 is DerivedAccount ) {}
And than cast it as DerivedAccount
. so you get the following:
public class AccountBL<T> where T : BaseAccount, new()
{
public void TestMethod()
{
T obj1 = new T();
obj1.MyMethod1();
if (obj1 is DerivedAccount )
{
(obj1 as DerivedAccount).MyMethod2();
}
}
}
Here you have an executable example: https://dotnetfiddle.net/NwxPRt
Upvotes: 2
Reputation: 43896
If you want to use DerivedAccount.Method2()
, this wish already is a constraint. You obviously need T
to be DerivedAccount.
You could do something like that:
(obj1 as DerivedAccount)?.MyMethod2();
but I personally don't like to mix type casts and generics. If your method is generic, it means you don't care about the specific runtime type (except it should be BaseAccount
). Then adding type checks seems a little odd.
Upvotes: 3
Reputation: 109045
Define an interface that includes the members you want to access, and then restrict the type parameter to types that implement that interface.
public IMyInterface {
void MyMethod2();
}
public class AccountBL<T> where T : BaseAccounbt, new(), IMyInterface {
// Members can access T.MyMethod2()
}
Unlike other some languages, C# only allows reference to members on type parameters that fit the requirements imposed on the type parameters.
Upvotes: 3