Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it necessary to destroy the class instances in my loop?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading