473,471 Members | 1,715 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

C# Fundamentals (override, virtual, new)

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
Mar 12 '06 #1
5 4509
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.

Mar 12 '06 #2
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
"Marcel Hug" wrote:
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

Mar 12 '06 #3
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.

Mar 13 '06 #4
> 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
"A.Kahtava" wrote:
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.

Mar 13 '06 #5
A.Kahtava wrote:
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/ar...itancetax.aspx
for my view on it.

Jon

Mar 13 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Eric Johannsen | last post by:
I have a simple object that inherits from CollectionBase and overrides the Count property: namespace MyTest { public class CollTest : System.Collections.CollectionBase { public override int...
14
by: JPRoot | last post by:
Hi I use the following syntax to have events inherited from base to child classes which works nicely (virtual and override keyword on events). But I am wondering if it is a "supported" way of using...
8
by: JPRoot | last post by:
Hi M. Jeffrey Tan, Just hopping you didn't forget me? :) Thanks JPRoot ----- \"Jeffrey Tan\" wrote: -----
4
by: Jazper Manto | last post by:
hi what is the difference between virtual / override and new? until now i only knew the virtual / override thing. thanx for hint. Jazper //--- new ----------------------------------------...
5
by: Mark Broadbent | last post by:
Oh yes its that chestnut again! Ive gone over the following (http://www.yoda.arachsys.com/csharp/faq/ -thanks Jon!) again regarding this subject and performed a few of my own tests. I have two...
11
by: z_learning_tester | last post by:
Hello, yes another beginner question that I'm sure is obvious to many here :-) My book is so bad. Really. It uses the exact same example of code for using the new kw and for using virtual(in the...
2
by: Adriano Coser | last post by:
Hello. After I converted my .net code to the new VC2005 syntax I started to get C4490 on my ExpandableObjectConverter subclass overrides. The GetProperties method is no longer called by the...
2
by: Shark | last post by:
Hi, if we need to change the behavior of operator new, it is called overriding or overloading? My other question is, if we change the behavior of operator new, do we use malloc to do that or we use...
2
by: Your_Persona | last post by:
Is there a way to get effect1 with the method in effect2? ///////////////////////////////////////////////////////////////////////////////////////////// using System; using...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.