Inheritance question

G

GregNga

I am new to C# and have a couple questions about using "abstract"

1) If you define a method as abstract do you have to specify abstract on the
class defintion as well or is it implied or can you have an abstract method
in a class that is not abstract
2) If you have a base class and a derived class that both have a method wit
the same signature, do you have to specify virtual on the base class method
and override on the derived class method if you want the derived class to use
the version of the method defined in the derived class
 
A

Alberto Poblacion

GregNga said:
1) If you define a method as abstract do you have to specify abstract on
the
class defintion as well or is it implied or can you have an abstract
method
in a class that is not abstract

If the class contains an abstract method, the class needs to be marked
also as abstract, otherwise you will get a compilation error.
2) If you have a base class and a derived class that both have a method
with
the same signature, do you have to specify virtual on the base class
method
and override on the derived class method if you want the derived class to
use
the version of the method defined in the derived class

If you mark the base method as virtual and the derived one as override,
you will get polymorphic behavior for the method, that is, if you assign an
instance of the derived class to the base class and then you invoke the
method on the base class, the derived method will execute.
If you don't want this, and instead you simply want to completely
separate methods with the same signature in both classes, you can just omit
the virtual and override keywords, but you will get a warning from the
compiler. You can avoid the warning by marking the method in the derived
class with the keyword "new". It is said that this method "shadows" the
method in the base class.
 
P

Peter Duniho

Alberto said:
[...]
If you don't want this, and instead you simply want to completely
separate methods with the same signature in both classes, you can just
omit the virtual and override keywords, but you will get a warning from
the compiler. You can avoid the warning by marking the method in the
derived class with the keyword "new". It is said that this method
"shadows" the method in the base class.

Or "hides". That said, hiding methods is generally a bad idea. I won't
go so far as to say there's never a good reason for doing it, but
usually it means there's something broken about the class design.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top