Tutorial by Examples

There are several places where you can use String.Format indirectly: The secret is to look for the overload with the signature string format, params object[] args, e.g.: Console.WriteLine(String.Format("{0} - {1}", name, value)); Can be replaced with shorter version: Console.WriteLine...
NumberFormatInfo can be used for formatting both integer and float numbers. // invariantResult is "1,234,567.89" var invarianResult = string.Format(CultureInfo.InvariantCulture, "{0:#,###,##}", 1234567.89); // NumberFormatInfo is one of classes that implement IFormatProvider...
public class CustomFormat : IFormatProvider, ICustomFormatter { public string Format(string format, object arg, IFormatProvider formatProvider) { if (!this.Equals(formatProvider)) { return null; } if (format == "Reverse") ...
The second value in the curly braces dictates the length of the replacement string. By adjusting the second value to be positive or negative, the alignment of the string can be changed. string.Format("LEFT: string: ->{0,-5}<- int: ->{1,-5}<-", "abc", 123); string....
// Integral types as hex string.Format("Hexadecimal: byte2: {0:x2}; byte4: {0:X4}; char: {1:x2}", 123, (int)'A'); // Integers with thousand separators string.Format("Integer, thousand sep.: {0:#,#}; fixed length: >{0,10:#,#}<", 1234567); // Integer with leading zero...
The "c" (or currency) format specifier converts a number to a string that represents a currency amount. string.Format("{0:c}", 112.236677) // $112.23 - defaults to system Precision Default is 2. Use c1, c2, c3 and so on to control precision. string.Format("{0:C1}"...
6.0 Since C# 6.0 it is possible to use string interpolation in place of String.Format. string name = "John"; string lastname = "Doe"; Console.WriteLine($"Hello {name} {lastname}!"); Hello John Doe! More examples for this under the topic C# 6.0 features: Stri...
string outsidetext = "I am outside of bracket"; string.Format("{{I am in brackets!}} {0}", outsidetext); //Outputs "{I am in brackets!} I am outside of bracket"
DateTime date = new DateTime(2016, 07, 06, 18, 30, 14); // Format: year, month, day hours, minutes, seconds Console.Write(String.Format("{0:dd}",date)); //Format by Culture info String.Format(new System.Globalization.CultureInfo("mn-MN"),"{0:dddd}",date); 6....
The ToString() method is present on all reference object types. This is due to all reference types being derived from Object which has the ToString() method on it. The ToString() method on the object base class returns the type name. The fragment below will print out "User" to the console....
While the String.Format() method is certainly useful in formatting data as strings, it may often be a bit overkill, especially when dealing with a single object as seen below : String.Format("{0:C}", money); // yields "$42.00" An easier approach might be to simply use the To...

Page 1 of 1