ERROR: use of unassigned local variable (for strin

2019-05-05 07:48发布

问题:

I am reading connection strings from my App.config file and for that i have following code.

try
 {
    string[] dbnames;
    int counter = 0;
    foreach (ConnectionStringSettings connSettings in ConfigurationManager.ConnectionStrings) 
    {
        dbnames[counter] = connSettings.Name;
        counter++;
    }
    return dbnames;
 }
 catch
 {
    throw;
 }

this code giving me error use of unassigned local variable for dbnames. i will have multiple connection strings in my App.config. They can be none,1,2 and so on. Depending on the needs. so i cant statically assign the dbname size. Because there can be a scenario if they exceed the value of assigned size. eg. if i assign it a size of 5, and what if i get 6th connection string. and if i have 1, then remaining 4 will be a memory wastage.

If i am wrong then let me know.

Thanks.

回答1:

Use this while initializing the array.

 string[] dbnames = new string[ConfigurationManager.ConnectionStrings.Count];

OR use List<string>



回答2:

You can't resize a System.Array dynamically like that.

Fortunately, there's no reason to do so. Use a different type of collection, like a List<T> instead. (Make sure you've added a using declaration for the System.Collections.Generic namespace!)

Like an array, a List<T> allows you to access the elements in the list by index, but it's also dynamically resizable at run-time, which fulfills the requirements in your question. And of course, since it's a generic method, it has the additional advantage (as compared to some of your other choices) of being strongly-typed. Since you're working with string types, you would use List<string>.

EDIT: There's absolutely no need for that empty try/catch block. Why catch an exception if you're just going to immediately rethow it? Just let it bubble up. In general, you shouldn't catch exceptions unless and only unless you can fix their immediate cause.



回答3:

You're declaring dbnames as a string array, but not defining it's size.

You'll need something like:

string[] dbames = new string[4];

where "4" is the length of your array.

If, however, you need a variable length you should use List<string>. In this case you can then add to it as necessary.



回答4:

As others have said, you could just use a List<string>. I would use LINQ to do all of this though, if you're using .NET 3.5 or higher:

return ConfigurationManager.ConnectionStrings
                           .Cast<ConnectionStringSettings>()
                           .Select(setting => setting.Name)
                           .ToArray(); // Or ToList
  • No need for a foreach loop (in your code - obviously it's there somewher :)
  • You can easily decide whether to return a list, an array, or simply IEnumerable<string>
  • No need for try/catch