Local variable not initialized

JasinCole

Well-known member
Joined
Feb 16, 2023
Messages
66
Programming Experience
1-3
I have the following code that complains about an unitialized variable in line 19
*EDIT* App.cs(35, 86): [CS0165] Use of unassigned local variable 'connectionString'

App Cctor:
string connectionString;

AppHost = Host.CreateDefaultBuilder()
            .ConfigureAppConfiguration((context, configuration) =>
            {
                configuration.Sources.Clear();
                //var environment = context.HostingEnvironment;

                configuration
                    .AddJsonFile("appsettings.json", true, true);

                var configurationRoot = configuration.Build();

                connectionString = BuildConnectionString(configurationRoot);
            })
            .ConfigureServices((context, services) =>
            {
                services.AddScoped<EmployeeRepository>();
                services.AddDbContext<SageDbContext>(options => options.UseSqlServer(connectionString));
            })
            .Build();
    }

I have this function that always returns a string and initializes the line 19 variable above

C#:
private static string BuildConnectionString(IConfiguration configRoot)
    {
        var connectionString = configRoot.GetSection(nameof(Database)).Get<ConnectionString>();
        return
            $"Server={connectionString?.Instance};" +
            $"Database={connectionString?.DatabaseName};" +
            $"Trusted_Connection=true;" +
            $"Encrypt=false";
    }

What's the logic here of the error that the variable is unitialized? I realize that all I need to do is initialize the variable, but I shouldn't have to twice. Isn't enough that BuildConnectionString() returns a guanranteed string enough for the compiler to know the error is erronious?
 
Last edited:
The compiler has no idea that the lambda that you have on lines 5-15 will always be executed by by the time the lines in the lambda on lines 17-20. Recall that the compiler does just a light static analysis. The setting of the variable is a runtime behavior.
 
It's too deep for the compiler to be able to work it out (and it's a bit janky too, tbh). If you're happy with it, just set it to default and move on with your life, or refactor the error away by making the code more structured
 
Back
Top Bottom