1

I have a string array of names, and I want all the names to be in all caps. This is my simple code, but it does not do anything to the names.

foreach (string x in names)
    {
        x.ToUpper();
        Console.WriteLine("{0}", x);
    }
  • None of the answers actually exchanges the entries in the string array. One way of doing that is: `for (var idx = 0; idx < names.Length; idx++) { names[idx] = names[idx].ToUpper(); }` – Jeppe Stig Nielsen Feb 12 '18 at 07:55

3 Answers3

4

You are not assigning back into the string (which is not required as well) do this -

foreach (string x in names)
{
    Console.WriteLine("{0}", x.ToUpper());
}

From MSDN

Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.

Community
  • 1
  • 1
Sadique
  • 22,572
  • 7
  • 65
  • 91
2

You can also use:

names.ForEach(x => Console.WriteLine(x.ToUpper()));

Also, you must know that:

x.ToUpper(); creates new object in memory. And returns a copy of this string converted to uppercase. So you must assign it to a new varible:

string X = x.ToUpper();
Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
0

Strings are immutable. So a new string is created which you need to assign to x.

    foreach (string x in names)
    {
        var y = x.ToUpper();
        Console.WriteLine("{0}", y);
    }
Amit Joki
  • 58,320
  • 7
  • 77
  • 95