C# Questions
-
Simply because C# doesn't try to "guess" what you wanted. Think about it: I don't want the system creating a new instance every time I try to use an existing one, because it means a trip to the DB and back to create an item that I may not use again - and the "real" DB item then doesn't get updated. I want the system to create an instance only when I specifically tell it to. If the system created them for me, then
MyClass[] data = MyClass[10];
Would create an array of references to MyClass instances and the instances to fill it with. I may not want that: if MyClass always contains an enormous Bitmap (for example) that is a huge amount of time and memory being wasted, because I'm about to fill the array with the top ten instances from the DB when I call the method below it:
MyClass[] data = MyClass[10];
DAL.GetImageData(data, 10, "SEARCH CONDITION");But the system can't know that because it doesn't have any idea what the method does - it's in a separate DLL! The
new
keyword allow you to specify exactly when you want an instance created (and reminds you that this could take some time and / or resources when it does it)Those who fail to learn history are doomed to repeat it. --- George Santayana (December 16, 1863 – September 26, 1952) Those who fail to clear history are doomed to explain it. --- OriginalGriff (February 24, 1959 – ∞)
To add to your excellent reply: related is lazy initialization lazy initialization[^] The .net framework convenieitly offers direct support: the Lazy Class[^]
Erik Westermann