473,395 Members | 1,341 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Using new vs virtual and override question

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
writing some code in the derived class. It seems they both say "yes, use
this derived method, slightly modified, and don't use the original one in
the base class"

I know I'm missing something big here.
Any compare/contrast of using new vs using virtual and override much
appreciated.
If it's too long, maybe a reference to a good white paper or something(?)
Thanks!

Jeff
Nov 16 '05 #1
11 19425
Hi,

The difference between the override keyword and new keyword is that the former does method overriding and the later does method hiding.

Check out the folllowing links for more information...

<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vcwlkversioningtutorial.asp>

http://www.akadia.com/services/dotnet_polymorphism.html

Hope this helps...

--
Regards,
Madhu

Microsoft C# MVP | MCSD.NET
"z_learning_tester" wrote:
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
writing some code in the derived class. It seems they both say "yes, use
this derived method, slightly modified, and don't use the original one in
the base class"

I know I'm missing something big here.
Any compare/contrast of using new vs using virtual and override much
appreciated.
If it's too long, maybe a reference to a good white paper or something(?)
Thanks!

Jeff

Nov 16 '05 #2
z_learning_tester <so*****@microsoft.com> wrote:
Any compare/contrast of using new vs using virtual and override much
appreciated.


See http://www.pobox.com/~skeet/csharp/faq/#override.new

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #3
OK, the MSDN example looked great until this line of code: "MyBase mB =
(MyBase) mD;"
Never seen anything like it. Is this a cast?
Does that mean mD is cast to a MyBase type?
How about if that line was missing? would the output be the following
instead?

MyBase-Meth1
MyDerived-Meth2
MyDerived-Meth3

This is what I was (almost) expecting, until that crazy unexplained line
above.
Thanks!

Jeff

--------------------------------------------
public class MyBase
{
public virtual string Meth1()
{
return "MyBase-Meth1";
}
public virtual string Meth2()
{
return "MyBase-Meth2";
}
public virtual string Meth3()
{
return "MyBase-Meth3";
}
}

class MyDerived : MyBase
{
// Overrides the virtual method Meth1 using the override keyword:
public override string Meth1()
{
return "MyDerived-Meth1";
}
// Explicitly hide the virtual method Meth2 using the new
// keyword:
public new string Meth2()
{
return "MyDerived-Meth2";
}
// Because no keyword is specified in the following declaration
// a warning will be issued to alert the programmer that
// the method hides the inherited member MyBase.Meth3():
public string Meth3()
{
return "MyDerived-Meth3";
}

public static void Main()
{
MyDerived mD = new MyDerived();
MyBase mB = (MyBase) mD;

System.Console.WriteLine(mB.Meth1());
System.Console.WriteLine(mB.Meth2());
System.Console.WriteLine(mB.Meth3());
}
}

Output:
MyDerived-Meth1
MyBase-Meth2
MyBase-Meth3

"Madhu[C#-MVP]" <Ma*******@discussions.microsoft.com> wrote in message
news:9E**********************************@microsof t.com...
Hi,

The difference between the override keyword and new keyword is that the former does method overriding and the later does method hiding.
Check out the folllowing links for more information...

<http://msdn.microsoft.com/library/de...-us/csref/html
/vcwlkversioningtutorial.asp>
http://www.akadia.com/services/dotnet_polymorphism.html

Hope this helps...

--
Regards,
Madhu

Microsoft C# MVP | MCSD.NET
"z_learning_tester" wrote:
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
writing some code in the derived class. It seems they both say "yes, use
this derived method, slightly modified, and don't use the original one in the base class"

I know I'm missing something big here.
Any compare/contrast of using new vs using virtual and override much
appreciated.
If it's too long, maybe a reference to a good white paper or something(?) Thanks!

Jeff

Nov 16 '05 #4
OK, so I went throught the MSDN examples today and they say:

Override is used in the derived class to say "use this one instead of the
one in the base class" I am overriding the one in the base class.
New also says "use this one instead of the one in the base class" I am
hiding the one in the base class.

I still fail to see the difference if you override the base class or if you
hide it, you still get the same results: the one on the derived class is
used instead.

The only difference I could find is the exception below, where new must be
used on MyBaseC instead of virtual and override b/c you cannot use virtual
with static.

So my question is- is there anything that new does that override doesn't or
vice-verse?
Aside from being usable with static? What's the difference between hiding
and overriding, or do they both just say "ignore the base, use the derived"?

This is by far the most difficult concept I've found in C#.
All examples look the same...
Again, any help *much* appreciated.
Thanks!

Jeff
public class MyBaseC
{
public static int x = 55;
public static int y = 22;
}

public class MyDerivedC : MyBaseC
{
new public static int x = 100; // Name hiding
public static void Main()
{
// Display the overlapping value of x:
Console.WriteLine(x);

// Access the hidden value of x:
Console.WriteLine(MyBaseC.x);

// Display the unhidden member y:
Console.WriteLine(y);
}
}
Output
100
55
22"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
z_learning_tester <so*****@microsoft.com> wrote:
Any compare/contrast of using new vs using virtual and override much
appreciated.


See http://www.pobox.com/~skeet/csharp/faq/#override.new

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #5
Jeff... Using new breaks polymorphic behavior.
http://www.geocities.com/jeff_louie/OOP/oop8.htm

As for the cast. Reference variables have type. Objects have class.
http://www.geocities.com/jeff_louie/OOP/oop6.htm

Regards,
Jeff

*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #6
z_learning_tester <so*****@microsoft.com> wrote:
OK, so I went throught the MSDN examples today and they say:

Override is used in the derived class to say "use this one instead of the
one in the base class" I am overriding the one in the base class.
New also says "use this one instead of the one in the base class" I am
hiding the one in the base class.

I still fail to see the difference if you override the base class or if you
hide it, you still get the same results: the one on the derived class is
used instead.


The difference is what the *base* class will use if it calls the
method. The link I provided gave an example of the difference, saying
which would be called when.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #7

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
z_learning_tester <so*****@microsoft.com> wrote:
OK, so I went throught the MSDN examples today and they say:

Override is used in the derived class to say "use this one instead of the one in the base class" I am overriding the one in the base class.
New also says "use this one instead of the one in the base class" I am
hiding the one in the base class.

I still fail to see the difference if you override the base class or if you hide it, you still get the same results: the one on the derived class is
used instead.
The difference is what the *base* class will use if it calls the
method. The link I provided gave an example of the difference, saying
which would be called when.


Yep, that seems the part I was really missing, that seems the key!
These derived classes are not to be used on their own.
I think the WHOLE point is to put all these methods back into the base class
type by a cast, or into a base class type array, etc, then use that instance
of the base class type.

Their choice of verbage however, though I'm sure is very standard,
is also very unintuitive in regards to hiding because all the lingo seems
reversed.
That caught me up for so long...

After all, the base method that is "hidden"(by the derived class- using
"new") is the one that shows up!
The one that is "hidden" by the derived class using no kw at all, also shows
up.
Dang that's confusing.

Now override is the only one that seems to make sense,
if it overrides the base then it well, overrides it, and is used instead of
the base(great! :-)

// versioning.cs
// CS0114 expected
public class MyBase
{
public virtual string Meth1() //This one is "overridden" so it
doesnt show- OK :-)
{
return "MyBase-Meth1";
}
public virtual string Meth2() //This one is "hidden", so it shows!
{
return "MyBase-Meth2";
}
public virtual string Meth3() //This one is "hidden", so it shows!
{
return "MyBase-Meth3";
}
}

class MyDerived : MyBase
{ public override string Meth1() //This one "overrides" the base-
cool.
{
return "MyDerived-Meth1";
}
public new string Meth2() //Usually in life, the 'newer' thing
is used... {
return "MyDerived-Meth2" }
public string Meth3() //This one "hides" the base, so on
output, it is itself- hidden. {
return "MyDerived-Meth3";
}

public static void Main()
{
MyDerived mD = new MyDerived();
MyBase mB = (MyBase) mD;

System.Console.WriteLine(mB.Meth1());
System.Console.WriteLine(mB.Meth2());
System.Console.WriteLine(mB.Meth3());
}
}Output
MyDerived-Meth1
MyBase-Meth2
MyBase-Meth3
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #8
Sorry, I used one of the other folk's examples from MSDN in my last
response.
Your example is definitely one of the cleanest yet and I think actually
answers my questions('hiding' terminology aside ;-)

public class Base
{
public virtual void SomeOtherMethod()
{
}
}

public class Derived : Base
{
public new void SomeOtherMethod()
{
}
}

....

Base b = new Derived();
Derived d = new Derived();
b.SomeOtherMethod(); //calls base.SomeOtherMethod()
d.SomeOtherMethod(); //calls derived.SomeOtherMethod()

Just one last question- did you need to use 'virtual' here?
Would it make a difference without it?
Thanks again,

Jeff

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
z_learning_tester <so*****@microsoft.com> wrote:
OK, so I went throught the MSDN examples today and they say:

Override is used in the derived class to say "use this one instead of the one in the base class" I am overriding the one in the base class.
New also says "use this one instead of the one in the base class" I am
hiding the one in the base class.

I still fail to see the difference if you override the base class or if you hide it, you still get the same results: the one on the derived class is
used instead.


The difference is what the *base* class will use if it calls the
method. The link I provided gave an example of the difference, saying
which would be called when.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #9
z_learning_tester <so*****@microsoft.com> wrote:
Just one last question- did you need to use 'virtual' here?
Would it make a difference without it?


You can only override virtual methods - without the virtual modifier,
the override version wouldn't compile at all.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10

And, now, if you could compare "method overriding" versus "method
hiding"...:-)

HO

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #11
Sample:

public class MyBase1
{
public string Say()
{
Console.WriteLine("Base1");
}
}

public class MyBase2
{
public virtual string Say()
{
Console.WriteLine("Base2");
}
}

public class Child1 : Base1
{
new public string Say()
{
Console.WriteLine("Child1");
}
}

public class Child2 : Base2
{
public override string Say()
{
Console.WriteLine("Child2");
}
}
Child1 ch1 = new Child1();
Base1 bs1 = (Base11)ch1;

ch1.Say();
bs1.Say();

//this will produce following lines:
// Child1
// Base1

while this:

Child1 ch2 = new Child2();
Base1 bs2 = (Base2)ch1;

ch2.Say();
bs2.Say();

//will produce:
// Child2
// Child2

The conclusion:

"new" hides the base method, with a new one. So depending on the
invocation, one or another will be executed.

"override" replaces the base method.
This is very simplified explanation of course. It took me some time to
grok it as well :)

Sunny
In article <O1**************@tk2msftngp13.phx.gbl>, ha***@pacbell.net
says...

And, now, if you could compare "method overriding" versus "method
hiding"...:-)

HO

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 16 '05 #12

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

Similar topics

3
by: Ed | last post by:
Greetings! I'm trying to implement own collection BaseCollection (inherited from NameObjectCollectionBase class), but my attempt to override NameObjectCollectionBase virtual method public virtual...
20
by: Raymond Lewallen | last post by:
I read this on this website page http://www.vbip.com/books/1861004915/chapter_4915_06.asp: Unlike many object-oriented languages, all methods in VB.NET are virtual. Now in BOL, Under...
5
by: gouqizi.lvcha | last post by:
Hi, all: I have 3 class X, Y, Z class Y is a subclass of class X; class Z is a subclass of class Y; i.e. class Y : public class X class Z : public class Y
28
by: Jon Davis | last post by:
If I have a class with a virtual method, and a child class that overrides the virtual method, and then I create an instance of the child class AS A base class... BaseClass bc = new ChildClass();...
32
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
0
by: Hiroyuki Tanaka | last post by:
Hi All, I am trying to develop an application for a touch screen using buttons for the numeric pad with Completion ComboBoxes. At the moment I am having a problem sending the button presses to...
2
by: William Leary | last post by:
I'm creating a strongly-typed collection class, and am deriving from CollectionBase. I note in the docs that RemoveAt() is virtual, yet I am not able to override it. For the life of me, I cannot...
4
by: Phill | last post by:
I read in one of Jesse Liberty's books that: "Because ToString() is a virtual method in the base class Object, it is guaranteed to be available in every derived class." (P.179 Programming C#) ...
15
by: John Salerno | last post by:
Hi all. I have a question about virtual and override methods. Please forgive the elementary nature! First off, let me quote Programming in the Key of C#: "Any virtual method overridden with...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
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,...
0
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...
0
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...

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.