1

I'm a beginner in C# so I hope to get your help here. I just wanted to know why passing an array with a specific size adds a default element of value 0 to the HashSet. Example:

int[] arr = new int[4]; 
HshSet<int> myHashSet = new HashSet<int>(arr);
myHashSet.Count(); //The count is equal to 1 and the first element's value is zero.

Can you please explain to me why this happens? Is this behavior unique for HashSets only or does it also apply to the other generic collections?

A.H
  • 13
  • 2
  • 1
    [Use your debugger](https://idownvotedbecau.se/nodebugging/) to look at the contents of `arr`. If you don't understand how `HashSets` work [read the documentation](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.-ctor?view=netcore-3.1#System_Collections_Generic_HashSet_1__ctor_System_Collections_Generic_IEnumerable__0__). – Dour High Arch Jun 03 '20 at 02:15

1 Answers1

6

arr is initialized as an array of four zeros, since that's the default value for an int. You haven't actually given the array any specific values just initialized it with a length.

HashSets can not contain duplicate values so when you give it four zeros via its constructor the last three are discarded.

CRice
  • 12,279
  • 7
  • 57
  • 84