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();
In your second case you are creating a new object on the first line just to throw it away on the second line. Completely unnecessary.
Only your first example makes any sense in this case since in the second case you are immediately replacing the created list with the one returned by the method. Initializing a list to a new empty list makes sense in the cases where you are adding to that list or when it is possible that the method you are calling to populate the list may somehow result in a null value when you would otherwise expect an empty list.
Examples where I might use initialization to a new, empty list.
List<MyCustomClass> listCustClass = new List<MyCustomClass>();
listCustClass.AddRange( GetList() );
or
List<MyCustomClass> listCustClass = new List<MyCustomClass>();
try
{
listCustClass = GetList();
}
catch (SqlException)
{
}
return listCustClass;
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.
The new keyword is basically used to allocate space on the heap. If you are creating a value type (structs, etc...) you don't have to use the new keyword. However, reference variables have to be new'd before they are used.
In your above example, it seems as though GetList() is returning a reference that is of type List which would have been created (new'd) somewhere within the function. Hence in this scenario, new'ing is pointless.
You use the new
keyword to construct a new instance of an object. It is not clear from your question what the GetList
method does, but presumably it is either creating a new list (thereby moving the new
keyword somewhere else) or returning an existing list (which someone created at one point using new
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With