silhouette hustler
silhouette hustler

Reputation: 1763

Inheritance - target specific inherited class C#

I've got multiple inheritance, have a look at the example comment bellow to get a better understanding of what I am trying to do.

CompanyEventsView : BaseViewModelFor<CompanyEvents>
{
}

BaseViewModelFor<TSource> : BaseViewModel where TSource : class
{

    public BaseViewModelFor(IAggregator aggregator, IRepository<TSource> repository, int i) 
    {
        Aggregator = aggregator;
        var source = repository.GetKey(i);
        (this as CompanyEventsView).MapFromSourceObject(source); // (this as CompanyEventsView) how could I make this generic so if I inherit another class to point to it
    }
}

So what I would like to know is how to force (this as CompanyEventsView) bit so it's always pointing to the class that is inherited from BaseViewModelFor<>?

Upvotes: 1

Views: 176

Answers (2)

Maarten
Maarten

Reputation: 22955

I would not use a generic, but use an interface. As a different answer indicates, the base class cannot know which class inherits from it, so IMHO generics isn't the solution here.

One thing to watch out for is that you are calling derived-class-code from base-class-constructor, which is dangerous, since the derived object is not created fully yet.

public interface IFromSourceObjectMapper {
    void MapFromSourceObject(object source);    // TODO: Update parameter type
}

BaseViewModelFor<TSource> : BaseViewModel where TSource : class
{

    public BaseViewModelFor(IAggregator aggregator, IRepository<TSource> repository, int i) 
    {
        Aggregator = aggregator;
        var source = repository.GetKey(i);
        var mapper = this as IFromSourceObjectMapper;
        if (mapper != null) {
            (this as CompanyEventsView).MapFromSourceObject(source); // (this as CompanyEventsView) how could I make this generic so if I inherit another class to point to it
        }
    }
}

CompanyEventsView : BaseViewModelFor<CompanyEvents>, IFromSourceObjectMapper
{
    public void MapFromSourceObject(object source) { ... }
}

Upvotes: 3

openshac
openshac

Reputation: 5165

Unfortunately the base class can't know which class inherited from it. One option is to call the base constructor and then MapFromSourceObject in the ComponentsEventView constructor

public ComponentsEventView(...) : base(...)
{
   this.MapFromSourceObject(source)
}

This is based on the assumption that your implementation of ComponentsEventView will allow for this.

Upvotes: 1

Related Questions