views:

49

answers:

3

Imagine that I have a general class Person. Then I have specializations of that class, for example DanishPerson and BritishPerson.

Now I need a function that returns the correct instance of Persons, depending on what country they are in, or a way to easily determine what type of persons they are. So I have the function:

List<Person> GetPersonsByCountry(int countryId)
{
    // query database, and get list of Persons in that country using EF inheritance
    // return list of persons
}

The list of persons, contains objects that are either of type DanishPerson or BritishPerson. Depending on the type, I need to display the right ViewModel in my UI. So if the list contains danish persons of type DanishPerson, I need to display one UI that will show the danish specific properties (and more).

Now my question is how you do this the best way? I guess that I could always use an if/else using typeof, but I was hoping for a more elegant, and maybe generic way? I was thinking that there might be some patterns for doing this as it seems like a common problem to me, when dealing with specializations?

+2  A: 

You could use a Dictionary<K, V> to store the mappings between the country codes and the associated class type and then use LINQ method OfType to obtain just the instances of the type associated to the provided country code.

João Angelo
A: 

If the List object is homogenous (i.e it's always either populated with only Danish or British person objects then this little LINQ tidbit will work:

var list = GetPersonsByCountry(1);
if (list.OfType<BritishPerson>().Any())
     ShowBritishUI();
else
     ShowDanishUI();
erash
+1  A: 

You can use Dictionary to map behaviour according to the person type. Better yet create a Ibehaviour interface and inherit two classes from it one for British and one for Danish and encapsulate the different behaviour between the two.

When adding another person type requires creating a behaviour class and updating the Dictionary.

Create a dictionary (private member of the class):

Dictionary<Type, IBehaviour> mapper = new Dictionary<Type, IBehaviour>()
{
   {typeof(BritishPerson), new BritishPersonBehaviour()},
   {typeof(DanishPerson), new DanishPersonBehaviour()}
};

In the code:

Person person = ...
var behaviour = mapper[person.GetType()];
behaviour.ShowUI(); //or something like this
Dror Helper
Thank you Dror. Can you give me a short implementation example? Or maybe you know of an article describing it?
Tommy Jakobsen
Here you go - hope it helps
Dror Helper
Thank you very much. This seems like a good solution and I would try and implement it. Do you know of other ways to do it that I should be aware of?
Tommy Jakobsen