Let’s say I have declared the following classes:
class BaseClass{
/* properties, constructors, getters, setters etc. */
public static BaseClass Create(string url){
/*will return, depending on url, a BaseClass or a SubClass object*/
}
public void Method(){
/* some code here */
}
}
class SubClass: BaseClass{
/* other properties, constructors, getters, setters etc. */
new public void Method(){
/* some other code here */
}
}
Now in my Main method I would like to do something along the lines of:
BaseClass baseClass = BaseClass.Create(url);
if(baseClass.GetType()==typeof(SubClass)){
baseClass.Method();
}
The idea here, of course, is to use Method as it is implemented in SubClass. It may be a silly question but how do I do that? I can’t cast a base class into a subclass so I’m not sure…
EDIT
Clarified my question. Even though baseClass was declared as a BaseClass instance, baseClass is SubClass will return trueif url is such that Create returns a SubClass instance.
It looks like you might be looking for polymorphism, but I can’t be sure from the description. What is the concrete use case for what you’re trying to do?
If it doesn’t make sense for the base class to have an implementation, then declare the class and the method as abstract — this forces the derived classes to override the method, guaranteeing that any instantiated class instance will have a valid implementation.