C# String ToUpper() Method
In C#, the ToUpper() method is used to convert all characters in a string to uppercase. If a character has an uppercase letter, it is converted, otherwise, it remains unchanged. Special characters and symbols are unaffected. This method is commonly used for case-insensitive comparisons and text formatting.
Example 1: Basic Usage of ToUpper() Method
// C# program to demonstrate ToUpper() method
using System;
class Geeks
{
public static void Main()
{
// Declare and initialize a string
string s1 = "GeeksForGeeks";
// Convert string to uppercase
string s2 = s1.ToUpper();
// Print original and converted strings
Console.WriteLine("String Before Conversion: " + s1);
Console.WriteLine("String After Conversion: " + s2);
}
}
Output
String Before Conversion: GeeksForGeeks String After Conversion: GEEKSFORGEEKS
Explanation: In this example, the ToUpper() method converts all lowercase letters in the string "GeeksForGeeks" to uppercase, resulting in "GEEKSFORGEEKS"
Syntax of String ToUpper() Method
public string ToUpper();
public string ToUpper(System.Globalization.CultureInfo culture);
- Parameters: culture (optional): A CultureInfo object that defines culture-specific casing rules.
- Return Type: The method returns a new string in which all characters have been converted to uppercase.
Example 2: Using String.ToUpper()
// C# program to demonstrate ToUpper() method
using System;
class Geeks
{
public static void Main()
{
// Declare and initialize a string
string s1 = "This is C# Program xsdd_$#%";
// Convert string to uppercase
string s2 = s1.ToUpper();
// Print the converted string
Console.WriteLine(s2);
}
}
Output
THIS IS C# PROGRAM XSDD_$#%
Explanation: In this example, all alphabetic characters in the string are converted to uppercase, while special characters remain unchanged.
Example 3: Using String.ToUpper(CultureInfo)
// C# program to demonstrate
// ToUpper(CultureInfo) method
using System;
using System.Globalization;
class Geeks
{
public static void Main()
{
// Declare and initialize a string
string s1 = "This is C# Program xsdd_$#%";
// Convert string to uppercase using
// English (United States) culture
string s2 = s1.ToUpper(new CultureInfo("en-US", false));
// Print the converted string
Console.WriteLine(s2);
}
}
Output
THIS IS C# PROGRAM XSDD_$#%
Explanation: In this example, the ToUpper(CultureInfo) method allows specifying a culture for case conversion. It ensures the consistency across different language settings.
Notes:
- The ToUpper() method does not modify the original string, it returns a new uppercase string.
- If the CultureInfo parameter is null, an ArgumentNullException is thrown.
- This method is useful for case-insensitive operations, such as string comparisons.