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'
I have this function that always returns a string and initializes the line 19 variable above
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?
*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: