18

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
  • 61,417
  • 20
  • 137
  • 189
user4891
  • 897
  • 2
  • 9
  • 14

3 Answers3

47

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
  • 1,107
  • 1
  • 14
  • 30
Jeff Yates
  • 61,417
  • 20
  • 137
  • 189
  • 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://learn.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
  • 75,627
  • 68
  • 187
  • 294
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
  • 50,229
  • 9
  • 102
  • 115