C# initialiser conditional assignment

Pomber picture Pomber · Jul 12, 2010 · Viewed 14.8k times · Source

In a c# initialiser, I want to not set a property if a condition is false.

Something like this:

ServerConnection serverConnection = new ServerConnection()  
{  
    ServerInstance = server,  
    LoginSecure = windowsAuthentication,  
    if (!windowsAuthentication)
    {
        Login = user,  
        Password = password  
    }
};

It can be done? How?

Answer

SLaks picture SLaks · Jul 12, 2010

This is not possible in an initializer; you need to make a separate if statement.

Alternatively, you may be able to write

ServerConnection serverConnection = new ServerConnection()  
{  
    ServerInstance = server,  
    LoginSecure = windowsAuthentication,  
    Login = windowsAuthentication ? null : user,  
    Password = windowsAuthentication ? null : password
};

(Depending on how your ServerConnection class works)