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 5 4497
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.
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
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.
> 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.
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
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...
|
by: JPRoot |
last post by:
Hi M. Jeffrey Tan,
Just hopping you didn't forget me? :)
Thanks
JPRoot
----- \"Jeffrey Tan\" wrote: -----
|
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 ----------------------------------------...
|
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...
|
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...
|
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...
|
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...
|
by: Your_Persona |
last post by:
Is there a way to get effect1 with the method in effect2?
/////////////////////////////////////////////////////////////////////////////////////////////
using System;
using...
|
by: MeoLessi9 |
last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
|
by: Aftab Ahmad |
last post by:
Hello Experts!
I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
|
by: Aftab Ahmad |
last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below.
Dim IE As Object
Set IE =...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: marcoviolo |
last post by:
Dear all,
I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
| | |