user3953989
user3953989

Reputation: 1929

How to override a virtual base class property with a derived class property

I can't use override since the types don't match and I've read I shouldn't use new to hide it, so how would I accomplish this?

SearchBase and ResultBase will work for 80% of my entities but a few will need specific implementations.

This main problem I see is when I do use new it's all typed during compile time and looks good in the debugger but passing this object to System.Web.Mvc.Controller.Json() seems to have a problem serializing it and they come out null.

public class SearchBase<T>
{
    public virtual ResultBase result { get; set; } 
}

public class SearchImp : SearchBase<SearchImp>
{
    public override ResultImp result { get; set; }
}


public class ResultBase
{

}

public class ResultImp : ResultBase
{

}

Upvotes: 2

Views: 262

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

You could use this instead:

public class SearchBase<T, TResult> where T: ResultBase
{
    public TResult result { get; set; } 
}

public class SearchImp : SearchBase<SearchImp, ResultImp>
{
    public TResult result { get; set; }
}


public class ResultBase
{

}

public class ResultImp : ResultBase
{

}

This way you don't need to override anything (nothing really to override here) and you can keep it type-safe.

Upvotes: 2

Related Questions