3

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);

can i write

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

5 Answers5

2

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 ternary operator and is a nice way to shorten if else statements.

In C# 6 you can shorten your String.Format as well; for example

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

instead of

String.Format("Time: {0}, Action: {1}, Param: {2}" time, someaction, param)
Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
1

You can use something like :

string message = String.Format("Time: {0}, Action: {1}{2}",
    time,
    someaction,
    param ? String.Format(", Param: {0}",param) : ""  
);
napuzba
  • 6,033
  • 3
  • 21
  • 32
1

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 basically to add a further string and placeholder for the third parameter into the string only if the condition is met.

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
1

Very similar to the other answers but you can try this as well:

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

Here we are adding the param as another formatted string, and are included to the actual output only is the item is not null. Hope that this Example will explain things clearer than my words. Please take a look

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
1

Or this is nice and tidy if you are using a vs 2015+ / c#6 Coalesce with string interpolation

var message = $"Time: {time}, Action: {someaction}" + (param != null ? $", Param: {param}" : "");
TheGeneral
  • 79,002
  • 9
  • 103
  • 141