Returning a default value. (C#)

18,541

Solution 1

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;
    }

    ....

}

Solution 2

default(T)

Solution 3

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;
        }
    }

....

}

Share:
18,541
Ramazan
Author by

Ramazan

Updated on June 04, 2022

Comments

  • Ramazan
    Ramazan about 2 years

    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;
        }
    
        ....
    
    }