Rafael
Rafael

Reputation: 2039

What is the C# equivalent for java Collections emptySet()

In my code I would like to return an empty set.

In java I can use static emptySet() method of standard Collections class.

Does the equivalent method/constant exist for the C# ?

===== Part of the code:

    private static HashSet<string> CreateSetWithProcessedIds()
    {
        if (!File.Exists(processedIdsFilePath))
        {
            // return empty set here
        }


    }

Edit 2:

I would like to return an empty and immutable set, when there's no saved data present. If saved data present, I want to create a HashSet and return it to the caller process. Caller process will use this set in readonly mode.

Upvotes: 0

Views: 1039

Answers (2)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131581

Since the set is read-only, the return type should change to IReadOnlySet<T>. The IReadOnlySet interface provides set functionality without any modification methods. Returning IReadOnlySet means that the code won't even compile if someone tries to modify it.

private static IReadOnlySet<string> CreateSetWithProcessedIds()
{
    if (!File.Exists(processedIdsFilePath))
    {
        return Immutable.ImmutableHashSet<string>.Empty;
    }

    var mySet=new HashSet<string>();
    ...
    return mySet;

}

The ImmutableHashSet.Empty field contains a static immutable hashset instance which implements IReadOnlySet<T>, so it can be used whenever an IReadOnlySet<T> is needed.

The Immutable are similar to "normal" arrays, dictionaries and sets, but any modification operations return a new collection with the modified data instead of modifying the original. This means they're thread-safe for both reading and writing, and any changes are only visible to the modifying code.

Upvotes: 4

Monomachus
Monomachus

Reputation: 1478

You can use something like this if you find this cleaner than standard instantiation

HashSet<int> hs = Enumerable.Empty<int>().ToHashSet();

Upvotes: 0

Related Questions