-3
for (int i = 0; i < s.Length -1; i++)
{
  temp = s[i]; // no errors here
  s[i] = s[j]; //Property or indexer string.this[int] cannot be assigned to -- it is read only
  s[j] = temp; //Property or indexer string.this[int] cannot be assigned to -- it is read only
}

I am dumb so please explain to me as if I was an 8 year old. Is this something you cannot do in C#? How do I fix this?

Beginner Programmer
  • 167
  • 1
  • 2
  • 11
  • 8
    What is `s`? According to the error it's a `string`, not an array (and `string`s are immutable in C#) – UnholySheep Jan 13 '18 at 22:45
  • 2
    There are numerous problems with your code, but let's focus on the main problem. You ask how to swap characters in an **array**, but my guess is that `s` is a **string**. Did you try with an array? – Lasse V. Karlsen Jan 13 '18 at 22:47
  • In C#, strings are not arrays of characters as they are in some languages. – Aluan Haddad Jan 13 '18 at 22:51
  • You might want to read [ask] and take the [tour] to use the site more effectively. phrases like *I am dumb so explain to me as if I was an 8 year old* arent well received at a `site for professional and enthusiast programmers`. – Ňɏssa Pøngjǣrdenlarp Jan 13 '18 at 23:41
  • Hi go through this link to learn more about swap methods in C# https://www.dotnetperls.com/swap – Maddy Jan 14 '18 at 00:31

1 Answers1

3

As others have already suggested s seems a string and thay are immutable so you have to convert s to a char array to do that. A possible way to do it would be:

char[] array = s.ToCharArray();
char temp = array[i];
array[i] = array[j];
array[j] = temp;
s = new string(array);
Becks
  • 468
  • 1
  • 5
  • 12