Reputation: 33
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...
Clarified my question. Even though baseClass was declared as a BaseClass instance, baseClass is SubClass
will return true
if url
is such that Create
returns a SubClass
instance.
Upvotes: 3
Views: 3747
Reputation: 13702
First of all: you have to initialise your variable as an instance of SubClass
, otherwise there is no way.
Then declare the method in the base class virtual
,
or
cast the object to SubClass
, and call the Method that way.
So either
class BaseClass{
/* properties, constructors, getters, setters etc. */
virtual public void Method(){
/* some code here */
}
}
or
((SubClass)baseClass).Method();
Upvotes: 0
Reputation: 23365
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?
class BaseClass{
public virtual void Method(){
Console.WriteLine("BaseClass");
}
}
class SubClass : BaseClass{
/* other properties, constructors, getters, setters etc. */
public override void Method(){
Console.WriteLine("SubClass");
}
}
static class Test
{
public void go() {
BaseClass instance = new SubClass();
instance.Method(); // prints "SubClass"
}
}
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.
Upvotes: 2
Reputation: 1278
Well I don't know why you would want to do that?
There is no way that the type of an instance of BaseClass
will be equal to the type of SubClass
.
That could only be possible if you created a instance of SubClass
and then cast it to BaseClass
. But in that case you could just cast it back to SubClass
to call Method()
Upvotes: 2
Reputation: 18102
If you instansiate the baseClass
as BaseClass
you will not be able to call the method as SubClass
, but if you write
BaseClass baseClass = new SubClass();
if (baseClass is SubClass)
{
SubClass subClass = baseClass as SubClass;
subClass.Method();
}
it will call the method as the SubClass
is defined.
Upvotes: 1