Reputation: 99428
If hasSecond == false
, I want to write
myString = string.Format(CultureInfo.InvariantCulture,
"{0}",
"first");
If hasSecond == true
, I want to write
myString = string.Format(CultureInfo.InvariantCulture,
"{0}{1}",
"first",
"second");
How can I combine them together?
For example, by using conditional expressions, the following doesn't seem work, because it doesn't make the fourth parameter optional:
myString = string.Format(CultureInfo.InvariantCulture,
"{0}" + (hasSecond == true ? "{1}" : string.Empty),
"first",
hasSecond == true ? "second" ; string.Empty);
when hasSecond==false
, it becomes
myString = string.Format(CultureInfo.InvariantCulture,
"{0}" + string.Empty,
"first",
string.Empty);
where we only have one place holder {0}
, while have two parameters "first"
and string.Empty
to fill it in.
Upvotes: 2
Views: 1013
Reputation: 23732
As I already wrote in my comment the second if condition is not necessary, because the variable will only appear in the string if it has the right place holder.
In this scenario the second variable will not end up in the string:
static void Main(string[] args)
{
double var1 = 99.9;
double var2 = 99.1;
bool condition = false;
string res = string.Format(CultureInfo.InvariantCulture, "{0}" + (condition ? "{1}" : string.Empty), var1, var2);
Console.WriteLine(res);
Console.ReadLine();
}
EDIT:
Comparing the Answer by Jianping Liu:
The only difference that I can see is that if you have a longer string and want to insert the values at certain positions than it might be more convenient to set the condition at the end and leave the second placeholder {1}
standing in all cases:
string res = string.Format(CultureInfo.InvariantCulture,
"The measurement revealed a value of: {0}{1} bla bla",
var1, condition ? " which strongly depends on the value of: " + var2 : string.Empty);
compare to:
string res = string.Format(CultureInfo.InvariantCulture,
"The measurement revealed a value of: {0}" +
(condition ? " which strongly depends on the value of: {1}" : string.Empty) +
" bla bla", var1, var2);
But I guess it is a matter of taste which one is more readable for you.
Upvotes: 1
Reputation: 982
myString = string.Format(CultureInfo.InvariantCulture,
"{0}{1}",
"first",
hasSecond ? "second" : string.Empty);
This should work
Upvotes: 4