nima khankhanizadeh nima khankhanizadeh - 4 months ago 10
C# Question

C# Generic Class, how can I use public properties of derived class of type parameter?

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.

Answer

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.

Comments