Question about [Pure] methods

devoured elysium picture devoured elysium · May 7, 2010 · Viewed 8.5k times · Source

Is the following method Pure? I'd say so, as it doesn't change in anyway the current class, thus, everything we can now currenly "see" in the class, before running this method will still be exactly the same after. Am I correct?

class Set {
    ...
    public ISet<T> UnionWith(ISet<T> set) {
       ISet<T> unionSet = ...

        foreach (Element element in this) {
            unionSet.Add(element);
        }

        foreach (Element element in set) {
           unionSet.Add(element);
        }

        return unionSet;
    }
}

Answer

Gabe picture Gabe · May 7, 2010

If by [Pure] you mean labeled with the Pure attribute from System.Diagnostics.Contracts, the documentation says:

Pure methods do not make any visible state changes.

Since your method appears to not make any visible state changes (i.e. no side effects), it would qualify for the [Pure] attribute.