Brett Romero wrote:
>>>I am curious why you have Foo( ) in BaseClass if Update( ) might not
exist to be called?
Update() will always exist.
John, I don't know what the type will be so this code doesn't work:
public void Foo()
{
if (this is Derived)
{
Derived d = (Derived)this;
d.Update();
}
}
I was trying to provide a simple example but the code does this:
public class BaseClass<T>{...}
public class MyClass: BaseClass<Person>, IClass<Person>{...}
I guess I'm not sure how your code would apply in this case.
In the end, how is your technique any better tham what I'm doing? We
are both still casting.
I can't use abstract because the base class has method bodies that do
something. In other words, it isn't an abstract class.
Thanks,
Brett
Hi Brett,
Update() will always exist.
I know you say that, but the compiler doesn't know that. It is conceivable
that you could create a derived class that does not implement an Update()
method. You need to instruct the compilre that Update() will always exist.
To do this, you define your base class as being abstract, and your Update()
method as abstract:
public abstract class BaseClass
{
public void Foo()
{
Update();
}
public abstract void Update();
}
An abstract class cannot be instantiated, however, and if you require this
functionality, remove the abstract modifiers, and define the Update()
method as virtual, and in your base class, provide no implementation:
public class BaseClass
{
public void Foo()
{
Update();
}
public virtual void Update()
{
}
}
Now, any derived classes from the abstract version MUST override Update():
public class DerivedClass : BaseClass
{
public override void Update()
{
// Implementation
}
}
Or, derived classes from the virtual version MAY override Update():
public class DerivedClass : BaseClass
{
public override void Update()
{
// Implementation
}
}
--
Hope this helps,
Tom Spink