Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to write only not null parameters with string.format [duplicate]

Tags:

string

c#

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

can i write

string message = String.Format(("Time: {0}, Action: {1}, Param: {2}!=null" time,someaction,param)
like image 271
DraganB Avatar asked Oct 19 '25 01:10

DraganB


1 Answers

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)
like image 171
Mighty Badaboom Avatar answered Oct 21 '25 15:10

Mighty Badaboom