简体   繁体   中英

c# Return value of function non-existent, when returning a dictionary

I have an interesting problem, which is a function that returns a Dictionary<String,HashSet<String>> .

The function converts some primitive structs to a Dictionary Class.

The function is called as follows:

Dictionary<String, HashSet<String>> Myset = new Dictionary<String,HashSet<String>>();
Myset = CacheConverter.MakeDictionary(_myList);

Upon execution of the two lines above, Myset is non-existent to the debugger. Adding a watch results in:

"The name 'Myset' does not exist in the current context"

public Dictionary<String, HashSet<String>> MakeDictionary(LightWeightFetchListCollection _FetchList) 
{
    Dictionary<String, HashSet<String>> _temp = new Dictionary<String, HashSet<String>>();
    // populate the Dictionary
    // return
    return _temp;    
}

The Dictionary _temp is correctly populated by the called function and _temp contains all the expected values.

The problem seems to be with the dictionary not being returned at all.

Examples I could find on the web of functions returning primitive Dictionary<string,string> work as expected.

Two things,

First, don't initialize the Myset with a new empty instance. The preferred way is to assign the result of the method call.

var Myset = CacheConverter.MakeDictionary(_myList);

Second, the odds are very strong that you are running in release mode. Typically the compiler will remove any code that is not being used.

Just as a side question, why are you creating a new Dictionary<String,HashSet<String>> and then discarding it?

Anyway, your code should be fine - I suspect it's something in the debugger that's playing up. The watch would only be able to see the variable when you're in the relevant method of course, given that it's a local variable.

Leaving the debugger aside from the moment, does the code actually run as expected?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM