Tag: Generic

When Parent-Child meets Inheritance

The right way to do inheritance in CSLA BO should be always adding generic in base/ancester’s class declaration.

e.g., instead of

class Car :BusinessBase {}

we should

class Car<T> :BusinessBase where T: BusinessBase<T> {}

Note: You will encounter the famous “dummy” staic field problem of CSLA.

The benefits of this includes,

  1. Don’t have to override base.Save().
  2. The registered property in base will get the correct type of inheritor.
  3. Child properties will always be aware the correct inheritor’s type T. (Maybe they shouldn’t)

But, this will cause the child_insert() much harder to write if you have child properties in base Car BO. This is invalid:

private void Child_Insert(Car<> parent)  {…}

And this doesn’t work either:

private void Child_Insert(object parent)  {
// Only check one level inheritance, to do recursive check, see details in this post.

if (!(parent.GetType().BaseType.GetGenericTypeDefinition()== typeof(Car<>)))
throw new NotSupportedException(“….”);

// Set parent id  , this line won’t compile.
LoadProperty<int>(CarIdProperty, ((Car<>)parent).CarId);


I can add generic to those child BO, but that looks too ugly, like Tire<T>, Seat<T>, they should be general, same to all the Cars.

Another solution is, creating an ICar interface.

private void Child_Insert(ICar parent)  {…}

It looks strange, but actually this can make child BO code much eaisier to write.