I have the feeling that my use of the interface is wrong. I know that an interface is a contract that a particular class must adhere to.
So, I will explain the problem I'm trying to solve, and maybe someone can point me in the right direction.
I am creating an application that returns a page for any request, I have three types of pages, Cms, Product and Category.
All three must implement the following interface:
public interface IPage { PageType PageType { get; set; } PageContent Content { get; set; } Meta Meta { get; set; } }
These properties are requested regardless of page type.
A page can have additional properties depending on their type, for example, a category page can be like this:
public class CategoryPage : IPage { public PageType PageType { get; set; } public PageContent Content { get; set; } public Meta Meta { get; set; } public List<Product> Products { get; set; } }
At the moment, I have a page service that will return a page for the requested URL.
Depending on the type of page it knows, what type of page should be returned.
The problem is that the pageService returns an IPage so that it can return any of the page types.
This is a problem, because not all of my concretes just implement the interface, in the case of a category page it also has a list, which, as expected, I can’t access unless I apply a specific type.
But is there a way to return the general type of the page and find out what the recipient is?
I am sure that as I do this, the moment is not the best way, and I would like to receive some direction and advice on how I can solve this small problem.
thanks
Update
I agreed to the cast.
I am sure that there should be a better way to deal with a situation where several classes use some basic properties, but also implement their own. when you get one of these classes from a service, you need to know what you have so that you can work with the appropriate properties.
Or maybe what I'm trying to do here is simply wrong, and I need to take a different approach. I think I will insist on what I have, but I continue to think about it.
Update 2
I changed the way I do this, so I don’t need to apply, I have a PageType enumeration that I use to determine the type of page that it works with.
Combined with an Ipage that inherits everything you need, it seems to be a pretty good solution and eliminates the need for casting.