C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Next: This example shows the ToLower method, but the other methods can be used in the same way. It lowercases constant string data.
First: The program first evaluates the TextInfo virtual property accessors on the InvariantCulture and CurrentCulture properties.
Tip: Include the System.Globalization namespace or specify the fully qualified name "System.Globalization.CultureInfo".
C# program that uses TextInfo
using System;
using System.Globalization;
class Program
{
static void Main()
{
//
// Access TextInfo virtual property accessors.
//
TextInfo textInfo1 = CultureInfo.InvariantCulture.TextInfo;
TextInfo textInfo2 = CultureInfo.CurrentCulture.TextInfo; // (FAST)
//
// Input mixed-cased strings.
//
const string value1 = "thedeveloperblog.com";
const string value2 = "SAM ALLEN 012345";
const string value3 = "sam allen";
//
// Use the ToLower method on the TextInfo variables.
//
string lower1 = textInfo1.ToLower(value1);
string lower2 = textInfo1.ToLower(value2);
string lower3 = textInfo2.ToLower(value3);
//
// Write lowercased strings to the screen.
//
Console.WriteLine(lower1);
Console.WriteLine(lower2);
Console.WriteLine(lower3);
}
}
Output
sam allen
sam allen 012345
sam allen
And: For this reason, they always carry the overhead of this virtual property access.
Thus: The string type methods have no difference in result values but are slower in some cases.
ToLowerNote: This is possible because you can hoist the virtual property access for TextInfo outside of a tight loop.
Note 2: This optimization is only useful when you are calling ToLower many times, in an important method.
Benchmark TextInfo used: C#
TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo;
Statements tested in separate loops: C#
string lower = textInfo.ToLower("SAMDOTNETPERLS");
string lower = "SAMDOTNETPERLS".ToLower();
ToLower TextInfo benchmark
Iterations: 10000000 iterations were tested.
TextInfo ToLower: 737 ms [faster]
String ToLower: 938 ms