Search code examples
c#.netarraysc#-4.0unassigned-variable

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


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.


Solution

  • Use this while initializing the array.

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

    OR use List<string>