Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Class Inheritance

I am working with insurance and have two different policy types - motor and household, represented by two different classes, Motor and Household.

Both have several bits of data in common, so both would inherit from another class called Policy. When a user logs into the app, they could have either a motor or a household policy, so the app needs to display the generic information and the information unique to Motor or Household. To encapsulate all this, i have a response object that has both a Motor member and a Household member, as shown below:

public class Response
{
    ...
    private MotorPolicy                 _motorPolicy;
    private HouseholdPolicy             _householdPolicy;
    ....
}

The code below should demonstrate:

if (response.PolicyType == Enumerations.PolicyType.Motor) 
{
    lblDescription.Text = response.MotorPolicy.Description;
    lblReg.Text = response.MotorPolicy.Reg;
}
else
{
    lblDescription.Text = response.HouseholdPolicy.Description;
    lblContents.Text = response.HouseholdPolicy.Contents;
}

The MotorPolicy doesn't have Contents property and the HouseholdPolicy doesn't have a Reg property.

But I really want to simply do:

if (response.PolicyType == Enumerations.PolicyType.Motor) 
{
    lblDescription.Text = response.Policy.Description;
    ...
}

I have tried using generics, could couldn't find the right solution.

like image 702
Neil Avatar asked Oct 05 '10 14:10

Neil


2 Answers

Your response only needs a Policy type, you can then store a MotorPolicy or HouseholdPolicy type into it.

Then your response just needs to check for data type

if (response.Policy is MotorPolicy) ....

Alternatively have an abstract method or a property returning data from an abstract method on the Policy type that is fully inplemented by the child classes and returns reg data or contents data as apporpriate.

like image 130
ChrisBD Avatar answered Sep 28 '22 13:09

ChrisBD


Each Policy descendant (now you have two, you might have more in the future, right?) should have their own UI controls which "know" how to deal with the policy information. The same approach can be used for other things, such as a "controller" for policy objects etc.

The response can then be made generic:

public class Response<T> where T: Policy {
    ...
    private T _policy;
    ....
}

Alternatively, you could have a more generic approach which uses reflection to display the information, but those are usually less "sexy" in their appearance and usability (think of the Property Grid in the VS designer).

like image 27
Lucero Avatar answered Sep 28 '22 13:09

Lucero