1

I have any number of variables string. I want to do something on them in method.

for example

string s1 = "s1";
string s2 = "s2";
List<string> list = new List<string>();
list.Add(s1);
list.Add(s2);
SomeMethod(list);
Console.Writeline(string.Format("{0} {1}, s1, s2)); 
// I want have here value after SomeMethod. Its possible without rewriting back from the list to variable???
void SomeMethod(List<string> list2)
{
 // do something with list2 for example list2[0] = "s11";
}

I want do it with params, but cant connect params with ref, so mayby its possible in list or array...

programis
  • 19
  • 1
  • 2
    Welcome to Stack Overflow. Did you *try* to do something with list2? For example, did you try assigning "s11" to `list2[0]`? If so, what outcome did you observe? If you pass an array or list into a method, the method doesn't get a copy of the array or list. It gets a reference to the actual array or actual list. If the method alters the array or list, it is altering *the same object* that the caller gave it. Arrays and lists are reference types. All classes are reference types. You don't need the `ref` keyword for those; it means something else. – 15ee8f99-57ff-4f92-890c-b56153 Aug 21 '19 at 12:43
  • 1
    The code above should work pretty well. What problem did you encounter specifically? – MakePeaceGreatAgain Aug 21 '19 at 12:45
  • I think OP wants to make `s1` and `s2` be modified inside `SomeMethod`. Is that right? – andresantacruz Aug 21 '19 at 12:46
  • 1
    When you put the _s1_ variable into the string with the Add method, you are inserting the reference to the "s1" string as the first element of the list. Now, if you change the first element in the list to have a different reference then your list will contain the new reference, but the variable _s1_ still has the same reference to the "s1" string. – Steve Aug 21 '19 at 12:48
  • Another function cannot change `s1` or `s2` **without passing `s1` / `s2` as a parameter** (specifically a `ref` parameter). – mjwills Aug 21 '19 at 12:49
  • Strings are immutable, you can´t change them in a method and expect that change to be reflected outside the method. You´d have to re-retreieve the new values from your list. – MakePeaceGreatAgain Aug 21 '19 at 12:49
  • To modify the `string` elements stored in the list, you need to actually replace the elements in the list. A `string` itself cannot be modified (so even though it's a reference type, you can't modify the objects in the list) and the variables `s1` and `s2` have nothing to do with the references in the list (so modifying those variables also has no effect). See marked duplicates for information on updating string values in lists. – Peter Duniho Aug 21 '19 at 16:26

0 Answers0