sarov
sarov

Reputation: 23

Using generics in a business object and collection

I have a base object abstract class and a base object collection class for some business objects to inherit from. I'm trying to figure out how to pass the base object type to the collection class (and other methods). I've been able to solve this by wrapping the class in an interface but i'm wondering if there is another way to do this or if using an interface is the best way. i think my question might make more sense from the code below.

i have a base class define -

public abstract class BaseObject<TYPE,KEY>:where TYPE:BaseObject<TYPE,KEY>, new()

public KEY ObjectId {get;protected set; }

i have a class that inherits from BaseObject

public class Customer : BaseObject<Customer,Guid>

My base collection class is -

public abstract class BaseObjectCollection<T> : List<T> where T: BaseObject, new()

I also have a few methods in other class that want to reference this baseclass -

public bool ValidateRule(BaseObject dataObject) {etc...}

Upvotes: 2

Views: 175

Answers (1)

competent_tech
competent_tech

Reputation: 44931

If you use the base class in other classes that are not also generics, then I'm afraid that you're going to have to specify the type and key parameters for the object when you pass it to methods like ValidateRule.

In this design, an Interface implemented by the base object is probably the most appropriate solution. We use this pattern extensively in our code and it works quite well.

One other item you could explore is reducing the complexity of the base class slightly by moving the Key into the class as an overridable (or must override) property that defaults to a string or int or whatever may be appropriate. We found that this approach (we forced all collection keys to be strings) significantly reduced the class complexity.

Upvotes: 1

Related Questions