if (!someList.Contains(new listItem(arg1, args2)))
{
// Do some stuff
}
For the code segment above, someList is a list of structs and listItem is the struct.
Does using the new operator in this context result in a memory leak? Or is this an example of bad practice in general? I have searched around on SO and Google, but wasn’t able to find a question that specifically addressed this.
You have to work really hard to create a memory leak in C#. It’s possible, but there are not very many cases where it happens accidentally (other than when inter-oping with other languages that don’t have such straightforward memory management). I won’t go into the edge cases here though.
Here is what the memory will look like for that object:
Containsreturns the parameters on it’s call stack will be “freed”, so we’re now back to just having one variable.Even though the
newkeyword is used, the structure is not created on the heap. It’s still created on the stack. In C#newis used when calling any constructor explicitly (barring reflection) and does not indicate an allocation on the heap (the way it does in, say, C++).It’s also worth mentioning that even if this were a class, and not a structure, it wouldn’t result in any memory leak. The object would end up on the heap, but the garbage collector will take care of cleaning it up at some point after it’s no longer needed. You’re not doing anything here that would result in holding onto a reference to the object once it’s not needed (and I know that
Containsisn’t going to do any shenanigans that would prevent it from being collected; if it was some unknown function it’s possible but unlikely that they’d do something mean).