70

To create an empty sequence one uses the following

var empty = Enumerable.Empty<string> ();

Is there an equivalent for creating an empty dictionary as easily as this?

4
  • What does it have to do with Linq?
    – walther
    Commented May 3, 2012 at 12:24
  • Sometimes google helps msdn.microsoft.com/en-us/library/xfhwa508.aspx
    – Likurg
    Commented May 3, 2012 at 12:26
  • 1
    Expected more pro question when rep ~2000. You are by using LINQ shooting a fly with cannon. Just use plain new Dictionary<string, string>(); Commented May 3, 2012 at 12:26
  • 12
    seems like a perfectly good question to me. There is string.empty and Enumerable.Empty why not Dictionary<string,string>.Empty. I can guess at implementation issues but its a perfectly reasonable concept;
    – pm100
    Commented Jun 13, 2013 at 22:26

8 Answers 8

57

Back to year 2019, there is a way to achieve this, using:

ImmutableDictionary<TKey, TValue>.Empty

More info can be found here (last couple of posts): https://github.com/dotnet/corefx/issues/25023

5
  • Is it limited to some newer versions? I can't seem to find it nor VS nor ReSharper knows about it? Also, is there another alternative otherwise?
    – jeromej
    Commented Apr 21, 2021 at 8:55
  • I manually found a port for .NET 4.0 on Nugget but sadly found out that foo?.ToDictionary(…) ?? ImmutableDictionary<Foo, Bar>.Empty does not compile. :(
    – jeromej
    Commented Apr 21, 2021 at 9:01
  • 1
    Not sure how I never saw this comment. The issue you have is obvious. ToDictionary() returns Dictionary<K,V>, while ImmutableDictionary<K,V>.Empty returns ImmutableDictionary<K,V>. Although both types implement similar interfaces (e.g. IDictionary<K,V>), the ?? operator doesn't know which type to use for the expression result. For example var a = foo?.ToDictinary<K,V>() ?? ImmutableDictionary<K,V>.Empty is ambiguous, but if you write IDictionary<K,V> a instead of var a the compiler will know what to cast the result of ?? operator into.
    – Mladen B.
    Commented May 6, 2022 at 20:26
  • As @Stefan mentions below the key is whether you need a Dictionary<K,V> or an IReadOnlyDictionary<K,V>. If you're talking about an immutable object then ImmutableDictionary<K,V>.Empty is what you're after. If you need a mutable dictionary than you'll need to allocate a new one each time because code could add items to the dictionary and you wouldn't want this to happen with a shared object.
    – ajz
    Commented Jul 5, 2022 at 21:47
  • I had to add (for a dot-net-core code base) this package ref PackageReference Include="System.Collections.Immutable" Version="a.b.c" 1.7.0 when I wrote this comment. Commented Jan 25, 2023 at 22:57
37

No there is no equivalent...

The purpose of Enumerable.Empty<T>() is to return a "cached" instance of an empty array. So you can avoid the overhead of creating a new array (return new T[0];).

You cannot translate this to a non-readonly structure like a IDictionary<TKey, TValue> or Dictionary<TKey, TValue> since the returned instance might be modified later and would therefore invalidate the purpose...

2
  • 18
    Yes, there is: ImmutableDictionary<TKey, TValue>.Empty
    – Mladen B.
    Commented Feb 27, 2019 at 10:11
  • As @stefan said - there isn't. However to achieve minimal allocations you can create your own static empty dictionary, e.x.: private static readonly Dictionary<string, string> EmptyDictionary = new Dictionary<string, string>() or even an extension to a static (actually cached overtime) single allocation
    – Adi
    Commented Sep 10, 2020 at 7:11
13

What's wrong with new Dictionary<string, string>()?

3
  • 8
    An empty Dictionary is mutable and might consume memory as you instanciate it multiple times. He might want a reference to a readonly empty IDictionary<string, string>.
    – Guillaume
    Commented May 3, 2012 at 12:29
  • @zx485, immutable empty data-structures are common -when you deal with immutable types- even this question mentions Enumerable.Empty. You can also take a look at the null object pattern but if you really want to know more, you can post a dedicated question here ;)
    – Guillaume
    Commented May 11, 2016 at 8:26
  • 2
    The reason for the existence of .Empty constructs in c# is to provide a convenient way of acquiring a static, cached, immutable instance of an empty representation of an object, which can be used in places where such objects are required, but not really used, in the code. If you construct a new object every time you just need an empty placeholder, for an object you don't really use, that beats the point of this whole concept.
    – Mladen B.
    Commented Feb 27, 2019 at 10:09
11

I assume that (at least now 5 years later) empty dictionary really means empty read-only dictionary. This structure is just as useful as an empty enumerable sequence. For instance you might have a configuration type that has a dictionary property (think JSON) that cannot be modified once it has been configured:

public class MyConfiguration
{
    public IReadOnlyDictionary<string, string> MyProperty { get; set; }
}

However, what if the property is never configured? Then MyProperty is null. A good solution to avoiding an unexpected NullReferenceException is to initialize the property with an empty dictionary:

public class MyConfiguration
{
    public IReadOnlyDictionary<string, string> MyProperty { get; set; }
        = new Dictionary<string, string>();
}

The downside is that each allocation of MyConfiguration requires an allocation of an empty dictionary. To avoid this you need something similar to Enumerable.Empty<T>(), i.e. a cached empty read-only dictionary.

There are two ways to achieve this. The first is to take a dependency on System.Collections.Immutable. An ImmutableDictionary<TKey, TValue> implementes IReadOnlyDictionary<TKey, TValue> and it has an Empty field that you can use:

IReadOnlyDictionary<string, string> empty = ImmutableDictionary<string, string>.Empty;

Or you can implement your own empty read-only dictionary similar to Enumerable.Empty<T>() and Array.Empty<T>(). Notice how the empty value is no longer a field and that the class is not generic. Instead it is a generic method. This requires two classes.

The first class is "hidden" and can be internal:

internal static class EmptyReadOnlyDictionary<TKey, TValue>
{
    public static readonly IReadOnlyDictionary<TKey, TValue> Instance
        = new Dictionary<TKey, TValue>();
}

The second class uses the first class but hides it behind the IReadOnlyDictionary<TKey, TValue> interface:

public static class ReadOnlyDictionary
{
    public static IReadOnlyDictionary<TKey, TValue> Empty<TKey, TValue>()
        => EmptyReadOnlyDictionary<TKey, TValue>.Instance;
}

Usage:

IReadOnlyDictionary<string, string> empty = ReadOnlyDictionary.Empty<string, string>();

For both solutions there will only be a single empty dictionary instance for each distinct combination of TKey and TValue.

2
  • Great explanation. I would add, if you already went to such an extent, it would be more appropriate to implement the IReadOnlyDictionary with an Empty property/method and not to reuse new Dictionary() in order to prevent addition of elements to that static instance (which was supposed to be empty throughout its lifetime) using a simple casting to Dictionary first (since it was created that way). For example ((Dictionary<K,V>)EmptyReadOnlyDictionary.Instance).Add(k, v) would spoil the emptyness, obviously.
    – Mladen B.
    Commented Mar 30, 2021 at 9:52
  • Even doing something like this would have the same effect ((Dictionary<TKey, TValue>)ReadOnlyDictionary.Empty()).Add(key, value)
    – Mladen B.
    Commented Mar 30, 2021 at 9:57
8

In .NET 8 preview it is possible to create an empty Dictionary by:

ReadOnlyDictionary<TKey, TValue>.Empty;

This way uses no memory and is faster than initiating it with the new keyword.

1

In C# 12 you can create an empty dictionary this way:

Dictionary<string, string> dict = [];
-1

When the key and value have the same type (e.g.: string):

Enumerable.Empty<string>().ToDictionary(x=>x, x=>x)
2
  • 4
    How is this better than new Dictionnary<string,string>() ?
    – disklosr
    Commented Dec 26, 2016 at 10:36
  • 1
    This is instantiating a new Dictionary each time you call it. Enumerable.Empty is an immutable structure, but ToDictionary() will create a fresh new Dictionary from it, which you don't want. You want an immutable empty dictionary.
    – Mladen B.
    Commented May 20, 2019 at 8:21
-1
Enumerable.Empty<KeyValuePair<string, object>>().ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
3
  • 3
    While this code may answer the question, it is better to explain what it does and add some references to it. Commented Jan 3, 2016 at 11:24
  • 1
    Same comment as for the @Bill Stanton's answer. This is instantiating a new Dictionary each time you call it. Enumerable.Empty is an immutable structure, but ToDictionary() will create a fresh new Dictionary from it, which you don't want. You want an immutable empty dictionary.
    – Mladen B.
    Commented May 20, 2019 at 8:23
  • you helped me :D
    – Diogo Cid
    Commented Jan 17, 2022 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.