简体   繁体   中英

C# Dictionary, what is the source of TryGetValue error in this simple code

        Dictionary<string, int> test = new Dictionary<string, int>();
        test.Add("dave", 12);
        test.Add("john", 14);

        int v;

        test.TryGetValue("dave", out int v)
        {

            Console.WriteLine(v);

        }

This simple C# code gives "Best Overload Method Match has some Invalid Arguments" error. Can you please tell me the source of the error? Thanks.

OP is in VS2012, not using C#7.

First, get rid of int in the parameter list. It can't be there in your version of C#.

Second, put a semicolon after the TryGetValue() call...

int v;
test.TryGetValue("dave", out v);
Console.WriteLine(v); 

Or put it in an if:

int v;
if (test.TryGetValue("dave", out v))
{ 
     Console.WriteLine(v); 
} 

Is "value" a variable you already declared or did you leave the example from the intellisense for TryGetValue? Pretty sure it's the latter case. edit: OR it's a new version of C# feature... This writes out 12 for v:

            Dictionary<string, int> test = new Dictionary<string, int>();
                    test.Add("dave", 12);
                    test.Add("john", 14);

                    int v;
                    test.TryGetValue("dave", out v);
                {
                            Console.WriteLine(v);

                    }

You got either a typo or a misunderstanding of

TryGetValue()

There is no need for the code block where your writeline sits in. Just end your line of code and do your writeLine.

test.TryGetValue("dave", out int value); // <---- notice the ;
Console.WriteLine(value);

EDIT: Or, as Mr.Nimelo suggests, there might be an if statement missing like so:

if test.TryGetValue("dave", out int value) 
{
  Console.WriteLine(value);
}

Don't you miss an if in your snippet, nope?

    Dictionary<string, int> test = new Dictionary<string, int>();
    test.Add("dave", 12);
    test.Add("john", 14);

    // missing if there?
    test.TryGetValue("dave", out int value)
    {

        Console.WriteLine(value);

    }

My cheap 2 cents with a bit of refactoring...:

    var test = new Dictionary<string, int> {{"dave", 12}, {"john", 14}};

    if (test.TryGetValue("dave", out var value))
    {
        Console.WriteLine(value);
    }

    Console.ReadKey();

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