Does using methods from internal classes without object initialization using new keyword cause memory leak in C# Winforms

104 views Asked by At

I see the following pattern used in the code a lot. Does this cause some form of Memory leak when used for large number of strings and string concatenation operations (millions of operations on strings of varying sizes).

pattern = (new CommonPattern(form)).ToString();

The class implementing the CommonPattern looks like this (after boiling down to code relevant to the question):

internal class CommonPattern {
    private string pattern;
    private TForm form;

    public CommonPattern(TForm form) {
        pattern = pattern + form.Name;
    }

    public override string ToString() {
        return pattern;
    }
}

I have tried adding a destructor like so.

~CommonDesignerPattern() { }

When calling this code in small projects we are not seeing any issues. However in projects with 150 – 200 forms we are seeing significant issue – leading to Out of memory Exception.

A memory profiler has not helped me in finding this issue. When I did the analysis, it pointed to String and byte[] as the final suspect, which did not help me.

I work on a small part of a very big project and wanted to learn if the call to new like it is used in the above code causes memory leaks and learn how to tackle this if it was a culprit.

Lot of search results online point to EventHandlers. But specifically I want to know if the case above can lead to a memory leak.

1

There are 1 answers

8
John Koerner On BEST ANSWER

There is no memory leak in the class code you posted. String concatenation does create additional instances of strings, however, once those strings are out of scope, they will eventually be cleaned up by the garbage collector.