C# – Implementing IDisposable correctly

cgarbage-collectionmemory-leaksmemory-managementnet

In my classes I implement IDisposable as follows:

public class User : IDisposable
{
    public int id { get; protected set; }
    public string name { get; protected set; }
    public string pass { get; protected set; }

    public User(int UserID)
    {
        id = UserID;
    }
    public User(string Username, string Password)
    {
        name = Username;
        pass = Password;
    }

    // Other functions go here...

    public void Dispose()
    {
        // Clear all property values that maybe have been set
        // when the class was instantiated
        id = 0;
        name = String.Empty;
        pass = String.Empty;
    }
}

In VS2012, my Code Analysis says to implement IDisposable correctly, but I'm not sure what I've done wrong here.
The exact text is as follows:

CA1063 Implement IDisposable correctly Provide an overridable implementation of Dispose(bool) on 'User' or mark the type as sealed. A call to Dispose(false) should only clean up native resources. A call to Dispose(true) should clean up both managed and native resources. stman User.cs 10

For reference: CA1063: Implement IDisposable correctly

I've read through this page, but I'm afraid I don't really understand what needs to be done here.

If anyone can explain in more layman's terms what the problem is and/or how IDisposable should be implemented, that will really help!

Best Answer

This would be the correct implementation, although I don't see anything you need to dispose in the code you posted. You only need to implement IDisposable when:

  1. You have unmanaged resources
  2. You're holding on to references of things that are themselves disposable.

Nothing in the code you posted needs to be disposed.

public class User : IDisposable
{
    public int id { get; protected set; }
    public string name { get; protected set; }
    public string pass { get; protected set; }

    public User(int userID)
    {
        id = userID;
    }
    public User(string Username, string Password)
    {
        name = Username;
        pass = Password;
    }

    // Other functions go here...

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing) 
        {
            // free managed resources
        }
        // free native resources if there are any.
    }
}
Related Topic