dotnetnoob
dotnetnoob

Reputation: 11360

Hash set - unique items not added

I have a class that contains the following:

    HashSet<CookieSetItem> _set = new HashSet<CookieSetItem>();

    public IEnumerable<CookieSetItem> Set
    {
        get { return _set; }
    }

    public void Add(int id)
    {
        id.ThrowDefault("id");

        var item = new CookieSetItem(id);

        if (_set.Add(item))
        {
            // this only happens for the first call
            base.Add();
        }
    }

When I call the add method multiple times, say with ID's 1,2,3 etc, only the first item is added.

Obviously I'm confused as a new CookieSetItem is being created each time with a unique element (the ID), so why is it not being added?.

For completeness, here's the cookie set class:

public sealed class CookieSetItem
{
    readonly DateTime _added;
    readonly int _id;

    public DateTime Added
    {
        get { return _added; }
    }

    public int ID
    {
        get { return _id; }
    }

    public CookieSetItem(int id)
        : this(id, DateTime.Now)
    {
    }

    public CookieSetItem(int id, DateTime added)
    {
        id.ThrowDefault("id");
        added.ThrowDefault("added");

        _id = id;
        _added = added;
    }
}

Upvotes: 0

Views: 146

Answers (1)

dotnetnoob
dotnetnoob

Reputation: 11360

Got to the bottom of it - more than one error, which clouded the overall view.

Firstly I updated my class with IEquatable, which fixed the adding problem. Secondly, I found that the end result which was to update a cookie with a string version of the hashset also failed due to the fact that it was not encrypted. Here's the amended class that fixed the original problem.

public sealed class DatedSet : IEquatable<DatedSet>
{
    readonly DateTime _added;
    readonly int _id;

    public DateTime Added
    {
        get { return _added; }
    }

    public int ID
    {
        get { return _id; }
    }

    public DatedSet(int id)
        : this(id, DateTime.Now)
    {
    }

    public DatedSet(int id, DateTime added)
    {
        id.ThrowDefault("id");
        added.ThrowDefault("added");

        _id = id;
        _added = added;
    }

    public bool Equals(DatedSet other)
    {
        if (other == null) return false;

        return this.ID == other.ID;
    }

    public override bool Equals(Object obj)
    {
        if (obj == null) return false;

        var ds = obj as DatedSet;

        return ds == null ? false : Equals(ds);
    }

    public override int GetHashCode()
    {
        return ID.GetHashCode();
    }
}

Thanks for the advice.

Upvotes: 2

Related Questions