Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of unassigned local variable 'dictionary'

Tags:

c#

dictionary

I got the error Use of unassigned local variable 'dictionary' despite I assigned the value in the following code:

private static void UpdateJadProperties(Uri jadUri, Uri jarUri, Uri notifierUri)
    {
        Dictionary<String, String> dictionary;

        try
        {
            String[] jadFileContent;

            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader(jadUri.AbsolutePath.ToString()))
            {
                Char[] delimiters = { '\r', '\n' };
                jadFileContent = sr.ReadToEnd().Split(delimiters, System.StringSplitOptions.RemoveEmptyEntries);
            }

            // @@NOTE: Keys contain ": " suffix, values don't!
            dictionary = jadFileContent.ToDictionary(x => x.Substring(0, x.IndexOf(':') + 2), x => x.Substring(x.IndexOf(':') + 2));

        }
        catch (Exception e)
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }

        try
        {
            if (dictionary.ContainsKey("MIDlet-Jar-URL: "))
            {
                // Change the value by Remove follow by Add

            }
        }
        catch (ArgumentNullException ane)
        {

            throw;
        }

    }

The error is from the line:

if (dictionary.ContainsKey("MIDlet-Jar-URL: "))

Can any one help me out here, pls? TIA

like image 259
Chris Avatar asked Dec 28 '25 16:12

Chris


1 Answers

You need to be explicit here:

Dictionary<String, String> dictionary = null;

There's the possibility it won't be assigned when you try to use it in your second try statement, for example if you throw an exception immediately in the first try, the dictionary wouldn't point to anything. This won't prevent a null reference exception (you'll have to handle that), it just makes your intent clear to the compiler.

like image 124
Nick Craver Avatar answered Dec 30 '25 06:12

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!