Inheritance and Generics

Inheritance and Generics

Old forum URL: forums.lhotka.net/forums/t/2026.aspx


dml posted on Monday, December 25, 2006

I am looking at an inheritance structure using generics, the following seems to be ok.
public abstract class ChemicalBase:Csla.BusinessBase<ChemicalBase>
public class Herbicide:ChemicalBase

I would like to try something like this:
public abstract class ChemicalBase<T>:Csla.BusinessBase<T>
public class Herbicide:ChemicalBase<Herbicide>

and get the following error when building the code:
The type 'T' must be convertible to 'Csla.BusinessBase<T>' in order to use it as parameter 'T'
in the generic type or method 'Csla.BusinessBase<T>'

JoeFallon1 replied on Monday, December 25, 2006

Be careful with Generics. They are not polymorphic. I suggest you implement your top level Base classes as generics (see other threads for samples of this) but then derive concrete classes from them as in your first example. By inserting a layer between CSLA and your BOs (the top level Base classes I referrred to) you can tweak how you want Csla to work and yet not worry about updating the framework each time it is revised. Plus you can add functionality to your base classes and all your BOs will pick them up instantly.

You may want to implement an Interface if you want polymorphic behavior.

Joe

 

dml replied on Monday, December 25, 2006

Thank you for that advice, will be a great help for how I carry on with this design. Any other opinions will be greatly appreciated

William replied on Tuesday, December 26, 2006

Define your base class as:
 
public abstract class ChemicalBase<T>
: Csla.BusinessBase<T> where T : ChemicalBase<T>
{ ... }
 
Then, you should be able to do:
 
public class Herbicide : ChemicalBase<Herbicide>
{ ... }
 
Regards,
William

sashidhar replied on Tuesday, January 09, 2007

How do I implement an interface for the above example?

 

Thanks in advance,

Sashidhar Kokku

Brian Criswell replied on Tuesday, January 09, 2007

public abstract class ChemicalBase<T>, IChemical
: Csla.BusinessBase<T> where T : ChemicalBase<T>
{ ... }

Copyright (c) Marimer LLC