ERROR: use of unassigned local variable (for string array)

孤人 提交于 2019-12-05 12:47:22

Use this while initializing the array.

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

OR use List<string>

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.

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.

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

declare it after class e.g

i am also writing code and i used to always encounter this problem

   public class ABC{
string[] array;
ABC()
{
}
//your_function_logics
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!