C# Fundamentals (override, virtual, new)

M

Marcel Hug

Hi NG !
I'm new in C# and I'm reading a book about the fundamentals and concepts.

In the chapter Methods it's written to use virtual, if i would like to
override the method in a subclass. This I've to do by using override.

It's also written, that's possible to "hide" the base class method by
using the new key word.

Because I've already written some C# code and I didn't know anything
about override and virtual I didn't use it, but it have been worked. So
i wrote some test code without using override and virtual to check this
aspect. It runs.

So now I have some question:

1.) Why do I have to use the override and virtual keys words, if it runs
without ? Is it for better readability ?

2.) When do I've to use virtual and override and when new ? I mean is
there a rule which describes in this case it should be used virtual and
override and in some other cases better use new ?

Thanks
Regards
Marcel
 
B

Bruce Wood

Virtual and override are useful only when you are using inheritance. If
you are just writing a single class then they serve no purpose.

Try writing code without them for a while. Once you start designing
hierarchies of classes, you will start to see a lot of duplicated code
in the parent and child classes, and wonder how to consolidate it. At
that point virtual and override will start to make a lot of sense.

Using "new" to hide parent class methods, properties, and events is
rare. I wouldn't worry about it until you become very familiar with
inheritance, and with virtual and override.
 
G

Guest

Hi Marcel,
1.) Why do I have to use the override and virtual keys words, if it runs
without ? Is it for better readability ?
2.) When do I've to use virtual and override and when new ? I mean is
there a rule which describes in this case it should be used virtual and
override and in some other cases better use new ?

When using inheritance if you have a base class which has a method called
X() and a derived class (a class that inherits from the base class) also has
a method called X() then the derived classes method X just hides the
implementation of the base class, but it does not override the implementation
of the base class. Meaning that if you refer to the derived class D with a
reference of type D you will see the code you implemented in D, however if
you refer to an instance of D with a reference of the base type B, then you
will get the code that runs in B, for example:

using System;

namespace ConsoleApplication21
{
class Program
{
static void Main(string[] args)
{
// "Print Person" is the output
Person p = new Person();
p.Print();

// "Print Man" is the output
Man m = new Man();
m.Print();

// "Print Person" is the output
Person manPerson = new Man();
manPerson.Print();

Console.ReadLine();
}
}

class Person
{
public void Print()
{
Console.WriteLine("Print Person");
}
}

class Man : Person
{
public void Print()
{
Console.WriteLine("Print Man");
}
}
}


The "new" keyword in this context is used to indicate that you realize that
there is a method in the base class you are hiding and you accept it. By
placing the "new" keyword on your derived classes method you are saying that
you realize there is method hiding taking place and you are okay with it.
This will stop the compiler warning you are getting. This is good because
you don't want this to take place silently behind your back because this
could cause significant bugs. In the code above the compiler would give you
the warning:

Warning 1 'ConsoleApplication21.Man.Print()' hides inherited member
'ConsoleApplication21.Person.Print()'. Use the new keyword if hiding was
intended. C:\test\ConsoleApplication21\Program.cs 35 21 ConsoleApplication21


Now if you don't want to just let people who inherit from a base class to
hide a method but completely replace the implementation you can mark the
method as virtual. People who want to replace the implementation then just
create a function with the same signature in the derived class and use the
override keyword. If we go back to the code example above and use the
virtual and override keyword you will see that now the output changes from:

Print Person
Print Man
Print Person

to

Print Person
Print Man
Print Man


using System;

namespace ConsoleApplication21
{
class Program
{
static void Main(string[] args)
{
// "Print Person" is the output
Person p = new Person();
p.Print();

// "Print Man" is the output
Man m = new Man();
m.Print();

// "Print Man" is now the output
Person manPerson = new Man();
manPerson.Print();

Console.ReadLine();
}
}

class Person
{
public virtual void Print()
{
Console.WriteLine("Print Person");
}
}

class Man : Person
{
public override void Print()
{
Console.WriteLine("Print Man");
}
}
}


Finally, you can still access the base classes implementation even if you
override it by using the base keyword, so in the above example from
Man::print you can call Person::print by saying base.Print(). This not only
allows you to replace the base implementation but also to extend it.

Now with great power come great responsibility, when using these methods it
is easy to break things and cause bugs, you should be aware of what you are
doing and what the base class is doing so that you do not have problems.

I hope that clears things up a bit for you.

Mark Dawson
http://www.markdawson.org
 
A

A.Kahtava

There are three basic types of inheritance:

An abstract overridable routine:
the derived class inherits the routine's interface but NOT it's
implementation.
In C# we use the "abstract" keyword.

An overridable routine:
the derived class inherits the routine's interface, implementation,
and is also allowed to override.
In C# we use the "override" and "new" keywords

A non-overridable routine:
the derived class inherits the routine's interface, implementation
and is NOT allowed to override.
In C# we use the "sealed" keyword.

note: routines can be either a function or procedure.

The primary goal of Software is to Manage Complexity. Inheritance works
against this goal and can often be avoided by using containment.
 
G

Guest

The primary goal of Software is to Manage Complexity. Inheritance works
against this goal and can often be avoided by using containment.

I would agree to that, good Object Oriented Design principles state that :

1. Design to an interface
2. Favour aggregation over inheritance.

People sometimes get carried away and have deep inheritance trees which
leads to added complexity and low code cohesion. Inheritance is very useful,
just need to keep it in check :)

Mark Dawson
http://www.markdawson.org
 
J

Jon Skeet [C# MVP]

A.Kahtava said:
There are three basic types of inheritance:

An abstract overridable routine:
the derived class inherits the routine's interface but NOT it's
implementation.
In C# we use the "abstract" keyword.

Or interfaces.
An overridable routine:
the derived class inherits the routine's interface, implementation,
and is also allowed to override.
In C# we use the "override" and "new" keywords

I think you mean "override" and "virtual". "new" is for method hiding.
A non-overridable routine:
the derived class inherits the routine's interface, implementation
and is NOT allowed to override.
In C# we use the "sealed" keyword.

You only need (and only *can*) use the "sealed" keyword when you wish
to override a method but prevent further overriding at the same time.
Methods are non-virtual by default in C#, fortunately.
note: routines can be either a function or procedure.

Not that there's any difference in C# (nor are those actually terms C#
uses). However, it is worth noting that events and properties can be
overridden as well as methods.
The primary goal of Software is to Manage Complexity. Inheritance works
against this goal and can often be avoided by using containment.

Sort of. There are plenty of times where inheritance makes things
simpler, but in itself it does tend to add complexity. See
http://msmvps.com/blogs/jon.skeet/archive/2006/03/04/inheritancetax.aspx
for my view on it.

Jon
 

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