virtual and abstract keywords

J

Jose Fernandez

Hello
I have been reading about the differences between virtual and abstract
keywords...

What i understand is that with VIRTUAL keyword, you can actually write the
whole method and override it if needed... with abstract, you just declare
the method name and must write the code in the inherited class. Am I right??

public class House{

public House(){}

public virtual string GetHouseName()
{
return "This is the House name Method"; // Virtual method implemented
}

public abstract string GetHouseNumber(); // Abstract method not implemented
}

public class DogHouse : House
{
public DogHouse(){}

public override string GetHouseName()
{
return "This is the override GetHouseName method";
}

public override string GetHouseNumber()
{
return "This is the number overrided method";
}
}
 
L

Laurent Bugnion

Hi,

I like to think of virtual as a "permission to override" and abstract as
an "obligation to override", though it's actually more an obligation to
implement.

BTW, override becomes overridden, not overrided ;-)

HTH,
Laurent
 
J

Jose Fernandez

jeje, Ok, overriden... i am improving my language too here... this works!!!

by the way, you can only have abstract methods in abstract class... Already
tested all the possible combinations and found out also that. You can have
virtual methods in abstracts class.

good wednesday
 
L

Laurent Bugnion

Hi,


Jose said:
jeje, Ok, overriden... i am improving my language too here... this works!!!

by the way, you can only have abstract methods in abstract class... Already
tested all the possible combinations and found out also that.

The thing is, as soon as you have one abstract method in the class, the
class automatically becomes abstract too. How can you create an object
when one part of its behaviour is unknown? Since C# is a very strict
language, abstract classes must be marked with the abstract keyword,
that's why you get a compiler error when you omit it.

HTH,
Laurent
 
C

Christof Nordiek

In addition to what others said:

Not only methods can be abstract. Also properties, events and indexers can
be abstract.
 

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