Posted by Leandro GR
on 12 December 2013 - 07:19 AM
Speaking of C# that's because variable declaration and object instantiation are two different things
Here we are just declaring a variable of type List<T> List<T> myList;
It has no value, and is not initialized, it can't be used unless it's used in an out parameter
What would happen if it automatically create a new instance of the object just by declaring it? If it was a value type, like an int or float there would be no problem at all, but it would never work for a reference type.
First of all a reference type may not have a parameterless constructor, or it could be an abstract class or even an Interface, there would be no way to initialize then this way, or it could have no public constructors at all, what if it uses some kind of factory class to initialize the objects?
And of course, what if you just want the variable to receive an instance from somewhere else? You do not always want a new object, sometimes you will receive it as a parameter or from calling some other function
So you say it's a "List<T>", but how can the compiler know you really want a "new List<T>" and not an existing one, or some other object that inherits from List<T>? What if you really want a new List<T> but you want it to be created by a function that initializes it with some values?
Both ways are easy to do, if I use decimal I just have to double the last value, but with hexadecimal I just have to remember the sequence 1, 2, 4 and 8 as it will just repeat itself over and over, just adding zeros to the end