473,761 Members | 8,933 Online
Bytes | Software Development & Data Engineering Community
+ 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 4534
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 ConsoleApplicat ion21
{
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.ReadLin e();
}
}

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

class Man : Person
{
public void Print()
{
Console.WriteLi ne("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 'ConsoleApplica tion21.Man.Prin t()' hides inherited member
'ConsoleApplica tion21.Person.P rint()'. Use the new keyword if hiding was
intended. C:\test\Console Application21\P rogram.cs 35 21 ConsoleApplicat ion21
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 ConsoleApplicat ion21
{
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.ReadLin e();
}
}

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

class Man : Person
{
public override void Print()
{
Console.WriteLi ne("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
5917
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 Count { get { return 0; }
14
12146
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 events since I never saw it used anywhere in MSDN documentation/samples?! Or it will just break when I upgrade to .NET Framework 2.x in the coming years namespace MyNamespac public delegate void MyDel() public class MyBase public virtual...
8
2895
by: JPRoot | last post by:
Hi M. Jeffrey Tan, Just hopping you didn't forget me? :) Thanks JPRoot ----- \"Jeffrey Tan\" wrote: -----
4
2220
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 ---------------------------------------- public class MyBaseA { public void Invoke() {}
5
2614
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 classes yClass which inherits xClass. xClass has a virtual method which simply writes a line of text stating its origin, yClass implements the same method which writes a line of text stating its origin also (i.e. "From yClass"). I ran the...
11
19460
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 base class) then override(in the derived class), but fails to compare and contrast the two... I've read this (short snippet)three times and by the looks of it they both do exactly the same thing- allow you to derive from the base and save...
2
4058
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 PropertyGrid when I use my subclass as a type converter. Can anyone tell me what has changed? What's the correct way to override GetProperties method? Here's the code for my class:
2
11521
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 operator new?
2
1326
by: Your_Persona | last post by:
Is there a way to get effect1 with the method in effect2? ///////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program
0
9988
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9923
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8813
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7358
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6640
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5266
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3911
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2788
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.