Suppose I have a loop which creates a new instance of a EF Class to add to databasde table in each loop iteration:
foreach (var record in records)
{
InvestmentTransactionStaging newRecord = new()
{
UserId = UserId,
InvestmentTransactionTypeId = interestRepaymentTransactionTypeId,
InvestmentEntityId = InvestmentEntityId,
Description = record.LoanReference,
Date = DateTime.Parse(record.Date),
};
_context.InvestmentTransactionsStaging.Add(newRecord);
}
Now normally, in the languages I am used to such as php it is not important destroy the instance after the call to _context..Add(), the garbage Collector takes care of it. If I omit this as I have above, would this then potentially cause any issues with memory in C#? Do I need to destroy the instance on each itertation that it is instamtiated and if so how? (I could not use the Disapose method as it complains the method is unavailable.
CodePudding user response:
Created objects are automatically destructed when no longer reachable
Meaning, any object created, lives only as long as the running code is still between curly braces, where it was instantiated
CodePudding user response:
TLDR: Even if you set newRecord
to null, you wouldn't have destroyed the class instance. It's still accessible in the _context.InvestmentTransactionsStaging
object. (In this case, _context
is probably a database.)
Long answer:
I might be getting into the weeds here, but your variable is just a pointer to a memory address where the class instance/object was created. When you null out that variable, you simply simply remove the value of the memory address from the variable, not the object. The object remains if other variables are pointing to the same memory address. Automatic garbage collection happens when that object's memory address is no longer being pointed to by any variables or other objects. This is when things get "destroyed".
This happens in many modern languages, not just C#. It might happen differently in C# than it does in PHP, but it ends up with similar results.
Even saying that the object is destroyed is not 100% correct, since the values aren't usually removed. The memory address is just used for something else and overwritten as needed. That can be within the same program or it could be returned to the OS for it to allocate to another process.
And this doesn't cover the complete lifecycle of objects, but it's the most useful explanation until you need to get into much lower level programming of microcontrollers and other embedded systems.