Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using the Collection Initializer of HashSet results in an empty HashSet (but compiles just fine) #1018

Closed
Malgefor opened this issue Apr 7, 2022 · 4 comments

Comments

@Malgefor
Copy link

Malgefor commented Apr 7, 2022

Hi!

When you use the collection initializer of a HashSet you end up with an empty HashSet, which I guess is the case because it is an immutable collection, but since I am creating the collection at that point in time and not modifying it after creation I was surprised to see my HashSet was empty. The thing is that this compiles just fine but at runtime the HashSet is empty. Below a comparison between the System and LangExt versions of the type:

using System.Collections.Generic;

using Shouldly;

using Xunit;

namespace Tests;

public class HashSetTest
{
    private static readonly LanguageExt.HashSet<string> HashSetLangExt =
        new()
        {
            "value1",
            "value2",
            "value3"
        };

    private static readonly HashSet<string> HashSetSystem =
        new()
        {
            "value1",
            "value2",
            "value3"
        };

    [Fact]
    public void LangExt_ShouldContainItems() => HashSetLangExt.ShouldNotBeEmpty(); // False

    [Fact]
    public void System_ShouldContainItems() => HashSetSystem.ShouldNotBeEmpty(); // True
}

I don't know if this is intended behavior or a bug, but it sure is confusing :P

(running the latest version of LangExt btw)

@louthy
Copy link
Owner

louthy commented Apr 7, 2022

There’s nothing I can do about that (as far as I am aware), this is a flaw in C#’s collection initialisation system. I believe it calls Add after construction, but obviously it’s an immutable collection. The crux of it is that you can’t use this.

instead use the construction function:

var ha = HashSet(1, 2, 3)

@louthy
Copy link
Owner

louthy commented Apr 7, 2022

There is a PR open which provides an analyser to warn about this, but it needs some work.

#868

@louthy
Copy link
Owner

louthy commented Apr 8, 2022

I also raised this as an issue on csharplang a while back, but it was basically ignored.

@Malgefor
Copy link
Author

Malgefor commented Apr 8, 2022

Ahh I thought something like that was the case, thanks for the explanation! The analyzer would be helpful indeed. Maybe we should tag this issue as documentation for visibility? Anyway, I will close this issue.

@Malgefor Malgefor closed this as completed Apr 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants