C# Memory Management Best Practices

In this article, learn C# Memory Management Best Practices by effectively managing memory in C# through proper code representation.


C# Memory Management Best Practices

The primary intention is to dispose, the unused objects from the heap and prevent promoting unused objects to a second or third generation.  The memory leak will be there if there is unused objects are stored in the heap even though they are of no use in the future. This will slow down your application that affects your application performance.

1. Using Keyword


using (var streamReader = new StreamReader("c:\\file.txt"))
{
    Console.Write(streamReader.ReadToEnd());
}

The above code is equivalent to disposing of an object explicitly in finally block

 
 
{
    var streamReader = new StreamReader("c:\\file.txt");
    try
    {
        Console.Write(streamReader.ReadToEnd());
    }
    finally
    {
        if (streamReader != null)
            streamReader.Dispose();
    }
}

2. IDisposable Interface

IDisposable is an interface with a single method Dispose. It allows consumers of the class to immediately release allocated unmanaged resources (such as file handles, streams, device contexts, network connections, and database connections). If the class doesn’t implement IDisposable, the consumer of the class has to wait a non-deterministic amount of time for the garbage collector when it performs object finalization.


public interface IDisposable
{
    void Dispose();
}

3. Using Statement with IDisposable Implementation

This example shows using a statement with a custom implementation of IDisposable. The Dispose method is called at the end of the using scope


using (var myDisposable = new MyDisposable())
{
    myDisposable.DoSomething();
}


public class MyDisposable : IDisposable
{
    public MyDisposable() { Console.WriteLine("Allocating resources"); }
    public void DoSomething() { Console.WriteLine("Using resources"); }
    public void Dispose() { Console.WriteLine("Releasing resources"); }
}

The output will be:
Allocating resources
Using resources
Releasing resources


– Article ends here –

If you have any questions, please feel free to share your questions or comments on the comment box below.

Share this:
We will be happy to hear your thoughts

      Leave a reply

      www.troubleshootyourself.com
      Logo