C# String.ToUpper method explanation with example

C# String.ToUpper method:

ToUpper method is used to convert a string to uppercase. We can use this method to convert a string to uppercase.

String is immutable in C#. We can’t change a string. ToUpper method doesn’t change the string. It creates one new string and returns that.

In this post, I will show you how to use ToUpper method with examples.

Definition of ToUpper:

ToUpper method is defined as like below:

public string ToUpper()

public string ToUpper(System.Globalization.CultureInfo? culture)
  • It returns the uppercase string.
  • We can also pass a specific culture. By default, it uses the current culture. It is an optional value.

Example of ToUpper:

Let’s take an example of ToUpper:

using System;
					
public class Program
{
	public static void Main()
	{
		string [] givenStrArr = {"Hello", "world", "123", "HelloWorld", "##$@"};

        foreach (string s in givenStrArr)
            Console.WriteLine("{0} => {1}", s, s.ToUpper());
	}
}

Here, givenStrArr is an array holding different strings. We are using a foreach loop to iterate over the strings in this array for each string, we are calling ToUpper.

It will print the below output:

Hello => HELLO
world => WORLD
123 => 123
HelloWorld => HELLOWORLD
##$@ => ##$@

Example with a culture:

Let’s modify the above example to use culture:

using System;
using System.Globalization;
					
public class Program
{
	public static void Main()
	{
		string [] givenStrArray = {"Hello", "world", "123", "HelloWorld", "##$@"};

        foreach (string s in givenStrArray)
            Console.WriteLine("{0} => {1}", s, s.ToUpper(new CultureInfo("en-US", false)));
	}
}

It will print the same output.

Different result for different culture:

We might get different results for different cultures. So, if you are comparing two objects with different cultures, it might not be equal. For example:

using System;
using System.Globalization;
					
public class Program
{
	public static void Main()
	{
		string s = "ireland";
		
		string str1 = s.ToUpper(new CultureInfo("en-US", false));
		string str2 = s.ToUpper(new CultureInfo("tr-TR", false));
		
		Console.WriteLine("str1: {0}",str1);
		Console.WriteLine("str2: {0}",str2);
		
		if(str1 == str2){
			Console.WriteLine("str1 and str2 are equal");
		}else{
			Console.WriteLine("str1 and str2 are not equal");
		}
			
	}
}

It will give:

str1: IRELAND
str2: İRELAND
str1 and str2 are not equal

The i is changed to I for the English-United states culture and İ for the Turkish-Turkey culture. So, both are not equal.

You might also like: