Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a default value. (C#)

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

    ....

}
like image 978
user4891 Avatar asked Dec 15 '08 03:12

user4891


People also ask

What is the default return type of main () *?

The normal exit of program is represented by zero return value. If the code has errors, fault etc., it will be terminated by non-zero value. In C++ language, the main() function can be left without return value. By default, it will return zero.

Which is the default value of a function without a return statement?

A function without an explicit return statement returns None . In the case of no arguments and no return value, the definition is very simple.

Does C automatically return 0?

In every C program you have to use return return 0; (or return -1;, or whatever... ), because the main function signature requires it. In a C++ program the statement is optional: the compiler automatically adds a return 0; if you don't explicitely return a value.

Does C return value?

Do you know how many values can be return from C functions? Always, Only one value can be returned from a function. If you try to return more than one values from a function, only one value will be returned that appears at the right most place of the return statement.


1 Answers

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

    ....

}
like image 50
Jeff Yates Avatar answered Oct 11 '22 23:10

Jeff Yates