Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# initialiser conditional assignment

Tags:

c#

initializer

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?

like image 584
Pomber Avatar asked Jul 12 '10 13:07

Pomber


2 Answers

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)

like image 109
SLaks Avatar answered Oct 14 '22 02:10

SLaks


You can't do this; C# initializers are a list of name = value pairs. See here for details: http://msdn.microsoft.com/en-us/library/ms364047(VS.80).aspx#cs3spec_topic5

You'll need to move the if block to the following line.

like image 21
Tim Robinson Avatar answered Oct 14 '22 00:10

Tim Robinson