Home > Mobile >  ISet vs HashSet in C#
ISet vs HashSet in C#

Time:02-13

I just have a general question as I am a C# 'newb'. Is there a reason to use ISet over HashSet when creating a Set?

class Program {

public static void Main(string[] args) 
{
ISet<string> myHashSet = new HashSet<string>();
myHashSet.Add("first");
myHashSet.Add("second");
myHashSet.Add("third");

// vs.

HashSet<string> myHashSet = new HashSet<string>();
myHashSet.Add("first");
myHashSet.Add("second");
myHashSet.Add("third");

}

}

I know ISet is in an 'interface' of HashSet I just don't understand why you would use ISet over HashSet or what difference it would make?

CodePudding user response:

In both statements, the myHashSet is actually of type HashSet.

The difference is: In the first case, the myHashSet is something that implements ISet, which might have some APIs different from HashSet.

For example:

interface ISet
{
    void method1();
    ......
}

class HashSet: ISet
{
    void method1();
    void method2();
    ......
}

Now

ISet set1 = new HashSet();  // set1.method1() is ok, but set1.method2() doesn't work!
HashSet set2 = new HashSet(); // set2.method1() and set2.method2() are all ok

CodePudding user response:

In the simple code you have submitted it is difficult to see the difference between using ISet and HashSet.

But consider a different situation, where instead of the code being in the Main() but in a method and the set data is passed in. Then the method would have the signature similar to :

void AddItems(ISet<string> repository)
{
    repository.Add("first"); 
    ...
}

The important thing to notice is that the method AddItems is responsible for Adding Items to the repository, but is not responsible for creating the repository. That responsibility is left to another component. That concrete instance of the repository is determined by the context in which the Add Item method is called. In real executable code, the underlying ISet<string> might be a HashSet<string>; in test code it might be a mock object exposing a ISet<string> interface. So using the abstraction ISet<string> in the method allows it to be used in very different contexts.

  •  Tags:  
  • c#
  • Related