C# String Theory—ToString method
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Articles |
| C# Articles |
| edit |
Contents |
ToString method
One of the most used methods when creating strings is the .ToString() method. Looking a little deeper you will find that value types have 4 versions of this method which allow for greater string formatting control.
Printing numbers
When printing numbers you may find yourself coding statements such as this:
if (imaginary >= 0) { strTemp = String.Format("{0}+{1}i", real, imaginary); } else { strTemp = String.Format("{0}{1}i", real, imaginary); }
However, with the .ToString(string format) statement, one can simplify the above to just one single line by removing the if statement and using sections of the format string instead.
strTemp = String.Format("{0}{1}i", real.ToString("#;-#;+0"), imaginary.ToString("+#;-#;+0"))
The easiest way to understand sections is to think of the possible states of the value:
| State | Case |
| 1 | value < 0
|
| 2 | value == 0
|
| 3 | value > 0
|
Sections are defined using the ; format specifier, when this is not used there is by default only one section. Therefore all 3 states' formatting are done in just the one section and so the same formatting is applied no matter what the state. As you may have guessed, up to 3 sections may be added corresponding to each state. The following pieces of code indicates how the states are formatted depending on the number of sections defined in the format string.
1 Section
int myNumber = 5; myNumber.ToString ("state 3 & state 2 & state 1");
2 Sections
int myNumber = 5; myNumber.ToString ("state 3 & state 2 ; state 1");
3 Sections
int myNumber = 5; myNumber.ToString ("state 3; state 1; state 2");
MSDN references
|

