Search code examples
c#dispose

IDisposable - what to Dispose in class without external references?


I have small helper classes. The classes are used internally to make sure that certain types of string always have the appropriate format (mail addresses, phone numbers, ids, urls, keys, colors, ...).

I wanted to put them into using blocks, to be able to recycle variable names:

using(Id id = ids.First())
{
    Container container = containers.getById(id);
    ...
}
foreach(Id id in ids.Skip(1))
{
    Container container = containers.getById(id);
    ...
}

As I did this, Visual Studio asked me to mark these classes as Disposable, which I did, but I am not sure what to do with the method stub. Let's take a "Mail Address" class as an example:

public class MailAddress : IEquatable<MailAddress>, IDisposable
{
    const string MAILADDRESSPATTERN = ...
    protected string _address;
    public MailAddress(string address)
    {
        if (address == null) throw new ArgumentNullException("address");
        if (!Regex.IsMatch(address, MAILADDRESSPATTERN)) throw new ArgumentException("address");
        this._address = address.ToLower();
    }

    bool IEquatable<MailAddress>.Equals(MailAddress other)
    ...
    public override int GetHashCode()
    ...
    ...
    ...
    public override string ToString()
    ...

    public void Dispose()
    {
        throw new NotImplementedException();
    }
}

What exactly would the Dispose function have to do in such a class? What do I have to dispose of, and what would the Garbage Collector do automatically?

Up to now, I didn't call Dispose on that class anywhere, and it seemed to work fine. Now, that the class is Disposable, do I have to add calls to Dispose throughout the code?


Solution

  • Your Dispose method has no purpose at all since you don't seem to have any unmanaged resources. Dispose is only useful in the case you want to manually dispose those resources.

    All managed resources are garbage-collected by the GC, so no need for any action on your side. Removing the IDisposable on your class seems to be the appropriate action. That would require to remove the useless using too, which you can exchange for simple brackets:

    {
        Id id = ids.First();
        Container container = containers.getById(id);
        ...
    }