0

What I want to do: create a function that takes a string and a single char as input. The function then shall "flip" every char according to the input char to a lower or upper case char.

My Problem: I want to do this with a ref string input, therefore the string gets changed in the function directly without the need to create a new string in the function.

Here is the simplified code:

 static void Flip(ref string input)
    {

        input[0] = 'a';

    }

The Problem: Error message -> Property cannot be assigned to, it is read only.

My Question - how can I change that?

What I COULD do is: input = "whatever", but if I want to index through the different letters in the string with input[i] and change those, it's not possible!

Since I'm new to the "ref" subject - why is this, and how do I fix it?

Thanks!

seaotternerd
  • 6,298
  • 2
  • 47
  • 58
wftico
  • 73
  • 1
  • 9
  • how did you invoked Flip function? was it `Flip(yourInputString)` or `Flip(ref yourInputString)`? – har07 Nov 23 '13 at 10:19

1 Answers1

2

Strings are immutable that's why its indexer is read only from which you can only read and not write into.

Indexer for string - public char this[int index] { get; }

Instead you should use StringBuilder which is mutable hence its indexer is not read only and you can do in place edits in object.

Indexer for stringBuilder - public char this[int index] { get; set; }

static void Flip(ref StringBuilder input)
{
   input[0] = 'a';
}

Refer to this for difference String vs StringBuilder.

Community
  • 1
  • 1
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185