Re: Use 'new' keyword...

Peter Osucha <[email protected]> Thu, 2 Nov 2006 15:27:40 -0500
Newsgroups gmane.comp.windows.devel.dotnet.cx
Message-ID <!&!AAAAAAAAAAAYAAAAAAAAAAh8puEHa/pGoCBtuLk0pZnCgAAAEAAAAJNChRr4LGlHmjyRT/[email protected]>
> You probably already know this, but just in case you don't:
> you should also think about if "new" is really the right
> choice. In practice, "new" means your objects will have two
> methods of the same name (and parameter lists), which can be
> confusing.
>
> Consider this:
> B b1 = new B();
> A b2 = new B(); // this works because B is a subclass of A
>
> b1.Copy(); // calls B's Copy -> returns a new B object, a
> copy of b1
> b2.Copy(); // calls A's Copy -> returns a new A
> object, a copy of the "A part" of b2

Hold on - this one has me confused.  In my example, A is the 'smaller'
object.  B is (essentially) A with a few more properties (it's base is A).
I would think it is the other way.  I could create...

A first = new A();
B second = new A();

But I can't do...

A third = new B();
B fourth = new B();

Because the line with 'third' above would fail, right?

> In most cases, you actually want to use override instead of
> new, so that B's Copy method replaces the one defined by A,
> and b2.Copy will correctly create a full-featured B object as well.
>
> In those cases, where override is not what you want, you
> should think about using different names for the different methods.

Override is exactly what I want here.  That way, if B's 'Copy' method is
used, it creates an exact copy of the full featured B object. (Thanks!)

> (Side note: The .NET framework uses the term "cloning" for
> making copies of objects. There's also an interface
> ICloneable that can/should be implemented by objects that
> support being cloned.)

I did realize this.  I haven't done much to attempt to implement Icloneable
for these objects.  I purposely used the method name 'Copy' here instead of
'Clone' because (be it a good reason or a bad), I wanted to separate - in my
head at least - that I was manually copying the object to create a new one
instead of implementing the Icloneable interface.

Peter

===================================
This list is hosted by DevelopMentorĀ®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com