简体   繁体   中英

Conditional String.Format on integer number

Wanted to check if conditional string.Format is possible in C# on the basis value of a number.

For example

for boolean data type

bool rvalue = false;
string s = string.Format("{0:X;0;Y}", rvalue.GetHashCode());

this will return Y.

Similarly, is there any possibility of writing condition inside string.Format like if number>2 then print X else print Y

It took me some time to understand what you were trying to do with that expression, but I think I got it now.

The best I can come up with now is this:

int number = 3;
string s = string.Format($"{(number > 2 ? "X" : "Y")}");

Or:

int number = 3;
string s = string.Format("{0:X;0;Y}", number > 2 ? 1 : 0);

But this would make more sense to me:

int number = 3;
string s = number > 2 ? "X" : "Y";

You can do it by the following way;

   bool rvalue = false;
                    string s = string.Format("{0:X;0;Y}",
                    rvalue ? 0 : 1);

Why not simply build your format-string in front:

string format = rvalue ? "0:X" : "0:Y";
var result = myInput.Format(format);

Pretty clear and easy to extend when you have more complicated conditions:

switch (whateverCondition)
{
    case 1: format = "0:Z"; break;
    case 2: format = "0:X"; break;
    case 3: format = "0:Y"; break;
    default: format = "whatever";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM