There is a simple way to write only non-null parameters using string.format

Instead of writing something like this

if(param!=null){
   string message = String.Format("Time: {0}, Action: {1}, Param: {2}" time,someaction,param)
}else{                                                                   
string message = String.Format("Time:{0},Action:{1}" time,someaction);

      

I can write

string message = String.Format(("Time: {0}, Action: {1}, Param: {2}!=null" time,someaction,param)

      

+3


source to share


5 answers


Or is it nice and tidy if you are using vs 2015+ / C # 6 Coalesce with string interpolation



var message = $"Time: {time}, Action: {someaction}" + (param != null ? $", Param: {param}" : "");

      

+1


source


No, but you can write this

string message = param != null 
    ? String.Format("Time: {0}, Action: {1}, Param: {2}" time, someaction, param)
    : String.Format("Time: {0}, Action: {1}" time, someaction);

      

It's called the ternary operator and is a good shorthand way if there are other statements.

In C # 6, you can also shorten String.Format

; eg



$"Time: {time}, Action: {someaction}, Param: {param}"

      

instead

String.Format("Time: {0}, Action: {1}, Param: {2}" time, someaction, param)

      

+2


source


You can use something like:

string message = String.Format("Time: {0}, Action: {1}{2}",
    time,
    someaction,
    param ? String.Format(", Param: {0}",param) : ""  
);

      

+1


source


Actually there is:

string message = String.Format("Time: {0}, Action: {1}, " + 
                 (param != null ? " Param: {2}" : string.Empty), 
                  time, someaction, param);

      

It looks a little unreadable though.

The idea is to add an extra string and placeholder for the third parameter to the string only if the condition is met.

+1


source


Very similar to other answers, but you can also try this:

string message = String.Format("Time: {0}, Action: {1}{2}",time,someaction,param==null?"":
                 String.Format(", param : {0}",param) );

      

Here we add param

as another formatted string and are included in the actual output only if the item is not null. Hope this Example will explain things more clearly than what I said. Please take a look.

+1


source







All Articles