Search code examples
c#c#-4.0mvp

Casting Derived Types and Dynamic Best Practices


I'm working on a project in C# 4.0. I have several presenter classes, which all inherit from the same base class. Each of these presenter classes has a "current" object, which is specific to each presenter, but they all also have a common inherited class, separate from the presenters, of course.

In terrible pseudo-code:

class ApplicationPresenter inherits BasePresenter
   Pubilc PersonApplication Current (inherited from Person)
class RecordPresenter inherits BasePresenter
   Public PersonRecord Current (inherited from Person)
class InquiryPresenter inherits BasePresenter
   Public PersonInquiry Current (inherited from Person)

...etc

Is there a way to make it so I can call "current" from any of these, without requiring type detection, but keep it in line with best practices?

The best option I have I think is to just make it a dynamic, as I know whatever I pass to it will have "current" and do it that way. Is that proper?

Or is there a way that I could create:

class BasePresenter
   Public Person Current

And make that cast appropriately?

I know there are ways around this, but I'm looking for clean and proper, for once.

Thank you!


Solution

  • Add generic type parameter to a base presenter so any derived concrete presenter would be able specifying custom Current item type:

    public abstract class PresenterBase<TItem>
    {
       public TItem Current { get; private set; }
    }
    
    // now Current will be of PersonApplication type
    public sealed class ApplicationPresenter : PresenterBase<PersonApplication>
    {
    }
    
    // now Current will be of PersonRecord type
    public sealed class RecordPresenter : PresenterBase<PersonRecord>
    {
    }