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
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 to share
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 to share
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 to share