Hi Mykl,
Hi all... I'm doing ok so far trying to learn C# on my own, but can't seem
to find the answer to this question...
When you instantiate objects, I'm just wondering, why in C# do you have to
go:
ObjectName varName = new ObjectName();
It seems redundant--- why wouldn't the designers of C# let you do this:
varName = new ObjectName();
You have to declare a type before you can create an object to store in it.
This is because the ability to inherit, in an OO language, allows you to
declare the variable to be of a 'parent' type while the object is of a
'child' type.
For example, let's say that you have an interface called ICollectionSorter
and you define different sorting routines, each inheriting your interface:
class QuickSort: ICollectionSorter
class BubbleSort: ICollectionSorter
etc...
Now, you can create a variable that will hold ANY of these objects by doing
this:
ICollectionSorter mysorter = new QuickSort();
Not so redundant now, is it? Your code can use the sorting routine by using
the methods defined in the interface. The code neither knows, nor cares,
which sorting routine you are using. You can substitute one for another
(the Liskov Substitution Principle at work).
In fact, in some circles, the ability to define a variable and create an
object of that type is considered a mixed blessing. It is better to
seperate the act of creating an object from the act of its use. Therefore
it would be preferable to say:
ObjectName var = ObjectFactory.MakeNewObjectName();
Johnathon Amsterdam published an article called 'Java's New Considered
Harmful' in DDJ that made this point for the Java language.
Scott Bain published an article called "The Perspectives of Use vs. Creation
in Object-Oriented Design" that makes this point for OO languages in general
and C# in specific.
The idea is the same: encapsulate the creation of an object and you buy
yourself considerable flexibility.
Either way, the designers of the language were cognizant of the fact that
defining an object is one activity and creating the object as an entirely
different activity.
That is why you have the name of the type appearing twice in your example.
--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik
Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.[/QUOTE]