Adding a single line if statement to string.format

Can you set the condition inside the string.format parameter.

So, if I have

string.format("{0}" , if x = 7 then return "SEVEN" else return "ZERO") 

Is there any way to do this?

+4
source share
4 answers

With the triple operator in VB.Net:

 String.Format("{0}", If(x = 7, "SEVEN", "ZERO")) 

Same thing in C # (as Brad already wrote):

 String.Format("{0}", x == 7 ? "SEVEN" : "ZERO") 
+4
source
 C# String.Format("{0}", x == 7 ? "SEVEN" : "ZERO") 

The ternary operator ( ?: In the line.

 VB.NET String.Format("{0}", IIf(x = 7, "SEVEN", "Zero")) ' Pre-Visual Studio 2008 String.Format("{0}", If(x = 7, "SEVEN", "Zero")) ' Visual Studio 2008 and forward 

In the line is the ternary method ( IIf() ) (Just like VS2008, short If() .

+2
source

Yes. In VB 2008 and above, the If statement is available:

 If(x = 7, "SEVEN", "ZERO") 

In VB 2005 and below, you need to use the IIf function :

 IIf(x = 7, "SEVEN", "ZERO") 

(And if your actual code is what you placed exactly, String.Format is completely redundant because it is already a string and you do not need to format it.)

+2
source

Sure! Use the "tertiary operator" (or actually called the "ternary operator") - like this:

 string.format("{0}", x == 7 ? "SEVEN" : "ZERO"); 
+1
source

Source: https://habr.com/ru/post/1387249/


All Articles