ERROR: using an unassigned local variable (for a string array)

I am reading the connection strings from my App.config file and for this I have the 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 gives me an error using an unrecognized local variable for dbnames. I will have some connection strings in my App.config. They can be nothing, 1,2 and so on. Depending on the needs. therefore, I cannot statically assign dbname size. Because there can be a scenario if they exceed the value of the assigned size. eg. if I assign it a size of 5, and what if I get the 6th connection string. and if I have 1, then the remaining 4 will be lost in memory.

If I am wrong, let me know.

Thanks.

+4
source share
5 answers

Use this when initializing an array.

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

OR use List<string>

+12
source

You cannot dynamically modify System.Array .

Fortunately, there is no reason for this. Use a different type of collection, such as List<T> . (Make sure you add a using declaration for the System.Collections.Generic namespace!)

Like an array, List<T> allows you to access items in a list by index, but also dynamically resize at runtime, which matches the requirements in your question. And, of course, since this is a general method, it has the additional advantage (compared to some of your other choices) that is strongly typed. Since you are working with string types, you should use List<string> .

EDIT: There is absolutely no need for this empty try / catch . Why catch an exception if you're just going to review it? Just let it bubble. In general, you should not catch exceptions, unless you can correct their immediate cause.

+5
source

You declare dbnames as a string array, but you do not specify its size.

You will need something like:

 string[] dbames = new string[4]; 

where "4" is the length of your array.

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

+2
source

As others have said, you can simply use List<string> . I would use LINQ to do all this, though if you are using .NET 3.5 or higher:

 return ConfigurationManager.ConnectionStrings .Cast<ConnectionStringSettings>() .Select(setting => setting.Name) .ToArray(); // Or ToList 
  • There is no need for a foreach loop (in your code - obviously, this is there somewhere :)
  • You can easily decide whether to return a list, an array, or just an IEnumerable<string>
  • No need for try / catch
+1
source

announce it after class for example

I also write code and have always come across this problem.

  public class ABC{ string[] array; ABC() { } //your_function_logics } 
+1
source

Source: https://habr.com/ru/post/1337293/


All Articles