Search code examples
c#.netnew-operatorallocation

To "new" or not to "new"


Is there a rule of thumb to follow when to use the new keyword and when not to when declaring objects?

List<MyCustomClass> listCustClass = GetList();

OR

List<MyCustomClass> listCustClass = new List<MyCustomClass>();
listCustClass = GetList();

Solution

  • In your scenario it seems that the actual creation of the object is being performed inside your GetList() method. So your first sample would be the correct usage.

    When created, your List<MyCustomClass> is stored in the heap, and your listCustClass is simply a reference to that new object. When you set listCustClass to GetList() the reference pointer of listCustClass is discarded and replaced with a reference pointer to whatever GetList() returns (could be null). When this happens your original List<MyCustomClass> is still in the heap, but no objects point to it, so its just wasting resources until the Garbage Collector comes around and cleans it up.

    To sum it up everytime you create a new object then abandon it, like the second example, you're essentially wasting memory by filling the heap with useless information.