Re: Use 'new' keyword...
Marc Brooks <[email protected]> Thu, 2 Nov 2006 15:30:00 -0600
| Newsgroups | gmane.comp.windows.devel.dotnet.cx |
|---|---|
| Message-ID | <[email protected]> |
> in A as virtual (so that B can override it), B.Copy will also need to return
> an object of type A (since that's what A's overridden method returned).
> Therefore, it seems I must use the 'new' keyword.
It will be declared to return an instance of type A, but since B isa
A, an instance of B can actually be returned from B's Copy() and
things will be just fine. In an instance where you KNOW that you are
expecting a B, it's safe to up-cast the returned value as needed.
Think this:
public class A
{
public virtual A Copy() { return new A(); }
public void Who() { Console.WriteLine(this.GetType().Name); }
}
public class B : class A
{
public override A Copy() { return new B(); }
}
public class Program
{
static int Main()
{
A a = new A();
a.Who();
A b = a.Copy();
b.Who();
B c = new B();
b.Who();
A d = b.Copy();
d.Who();
B e = (B)d.Copy();
e.Who();
}
}
Will print (ignoring any namespace...)
A
A
B
B
B
If it confuses you to think this is "safe", just substitute "object"
for A in the declarations mentally and see how that mirror nomal
use...
--
"We do not have the luxury of making that risky assumption that people
will not be affected by the potential change. I know this can be
frustrating for you as it is for us. Thanks for your understanding in
this matter.." --Some misguided soul at Microsoft
Marc C. Brooks
http://musingmarc.blogspot.com
===================================
This list is hosted by DevelopMentor® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com