16

I'm creating my own dictionary and I am having trouble implementing the TryGetValue function. When the key isn't found, I don't have anything to assign to the out parameter, so I leave it as is. This results in the following error: "The out parameter 'value' must be assigned to before control leaves the current method"

So, basically, I need a way to get the default value (0, false or nullptr depending on type). My code is similar to the following:

class MyEmptyDictionary<K, V> : IDictionary<K, V>
{
    bool IDictionary<K, V>.TryGetValue (K key, out V value)
    {
        return false;
    }

    ....

}
Jeff Yates
  • 58,658
  • 18
  • 135
  • 183
user4891
  • 787
  • 2
  • 8
  • 14

3 Answers3

45

You are looking for the default keyword.

For example, in the example you gave, you want something like:

class MyEmptyDictionary<K, V> : IDictionary<K, V>
{
    bool IDictionary<K, V>.TryGetValue (K key, out V value)
    {
        value = default(V);
        return false;
    }

    ....

}
Alex Telon
  • 867
  • 10
  • 27
Jeff Yates
  • 58,658
  • 18
  • 135
  • 183
  • 1
    Just tried to use 'default' and didn't realise I couldn't until I upgraded to C# 7.1. – Brett Rigby Sep 24 '17 at 08:38
  • @BrettRigby default was made available in C# 2. Running an empty CLI project with default(int) in C#1 (ISO-1 in Visual Studio) gets you this error: `Program.cs(11,31,11,38): error CS8022: Feature 'default operator' is not available in C# 1. Please use language version 2 or greater.` But using C#2 (ISO-2) or greater works fine. – Alex Telon Oct 17 '17 at 11:03
  • @BrettRigby However if you meant the use of `value = default` then you need [C# 7.1](https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-1#default-literal-expressions). – Alex Telon Oct 17 '17 at 11:21
7
default(T)
BCS
  • 67,242
  • 64
  • 175
  • 277
5
return default(int);

return default(bool);

return default(MyObject);

so in your case you would write:

class MyEmptyDictionary<K, V> : IDictionary<K, V>
{
    bool IDictionary<K, V>.TryGetValue (K key, out V value)
    {
        ... get your value ...
        if (notFound) {
          value = default(V);
          return false;
        }
    }

....

}

Strelok
  • 46,161
  • 8
  • 92
  • 112