As others mentioned, this can't exactly be done within an initializer. Is it acceptable to just assign null to the property instead of not setting it at all? If so, you can use the approach that others have pointed out. Here's an alternative that accomplishes what you want and still uses the initializer syntax:
ServerConnection serverConnection;
if (!windowsAuthentication)
{
serverConection = new ServerConnection()
{
ServerInstance = server,
LoginSecure = windowsAuthentication,
Login = user,
Password = password
};
}
else
{
serverConection = new ServerConnection()
{
ServerInstance = server,
LoginSecure = windowsAuthentication,
};
}
In my opinion, it shouldn't really matter much. Unless you're dealing with anonymous types, the initializer syntax is just a nice to have feature that can make your code look more tidy in some cases. I would say, don't go out of your way to use it to initialize all of your properties if it sacrifices readability. There's nothing wrong with doing the following code instead:
ServerConnection serverConnection = new ServerConnection()
{
ServerInstance = server,
LoginSecure = windowsAuthentication,
};
if (!windowsAuthentication)
{
serverConnection.Login = user,
serverConnection.Password = password
}