Re: new and override
- From: "Jonathan Allen" <x@xxx>
- Date: Fri, 3 Jun 2005 13:06:39 -0700
That won't work. I can just cast it to the base class and call the method.
A x = new B();
x.Print();
The real reason for the 'new' keyword is backwards compatibility.
Lets say I own class A and you own class B.
Your class B inherits from my class A. It has a print method, but mine does
not.
Six months later, I add a print method to my class A. You want to use the
new version of A, but want to keep using your version of print without
breaking mine. You add the 'new' keyword in your class, and thus any code
that was using your print will continue to do so. Unfortunately, any new
code that wants to use my print method has to cast the object to the base
type, but that is a small price for not breaking all your code.
You should never design code using the new keyword. Save it for situations
that you cannot control.
--
Jonathan Allen
"Eyal Safran" <eyal@xxxxxxxxxxx> wrote in message
news:1117821136.089125.79600@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
> yes, and also you can use new in order to change the access modifier of
> a method.
>
> so you can make a public method become protected or private.
>
> example:
>
> class A
> {
> /// <summary>
> /// The main entry point for the application.
> /// </summary>
> [STAThread]
> static void Main(string[] args)
> {
> object obj = new B();
> ((A)obj).Print(); // will work
> ((B)obj).Print(); // will not compile
> }
>
>
> public virtual void Print()
> {
> Console.WriteLine("A");
> }
> }
>
> class B : A
> {
> private new void Print()
> {
> Console.WriteLine("B");
> }
> }
>
> Eyal.
>
.
- References:
- new and override
- From: Josh Gilfillan
- Re: new and override
- From: Jeff Louie
- Re: new and override
- From: Eyal Safran
- new and override
- Prev by Date: Re: array question
- Next by Date: Re: Multiple instances of FileSystemWatcher ??????
- Previous by thread: Re: new and override
- Next by thread: Reading MapInfo file in C# - how?
- Index(es):
Relevant Pages
|