0

I am a little confused. I know a string is immutable, but how about a string array?

Whenever I add something to an empty array, does it create a new instance of that array?

How about when I change something in it?

string[] array = new string[5];

array[0] = "my favourite string"; //does it create a new instance of the array here?
array[0] = "changed that"; //how about now?
mas-designs
  • 7,498
  • 1
  • 31
  • 56
Henri Willman
  • 119
  • 1
  • 5
  • 7
    arrays are not immutable. – juharr Feb 19 '20 at 17:20
  • Array instance (and memory for it) is created when you use `new` operator in this line `string[] array = new string[5];`, you can have a look at [specs](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/single-dimensional-arrays) for details – Pavel Anikhouski Feb 19 '20 at 17:20
  • Thanks! I apologize for these beginner questions – Henri Willman Feb 19 '20 at 17:21
  • There are immutable collections in [System.Collections.Immutable](https://learn.microsoft.com/en-us/dotnet/api/system.collections.immutable?view=netcore-3.1) – juharr Feb 19 '20 at 17:22
  • I'm a little torn, no one asked this exact question to my knowledge, it's the inverse of this question: https://stackoverflow.com/questions/210428/are-immutable-arrays-possible-in-net/17852590#17852590 and the question could be easily tested... – Austin T French Feb 19 '20 at 17:24
  • 1
    To be as super-nit-picky as possible: any *empty* array is immutable, and that can be useful in itself. But any non-empty array is mutable. – Jon Skeet Feb 19 '20 at 17:50

1 Answers1

0

Here is the IL for your code ..

IL_0000:  nop         
IL_0001:  ldc.i4.5    
IL_0002:  newarr      System.String
IL_0007:  stloc.0     // array
IL_0008:  ldloc.0     // array
IL_0009:  ldc.i4.0    
IL_000A:  ldstr       "my favourite string"
IL_000F:  stelem.ref  
IL_0010:  ldloc.0     // array
IL_0011:  ldc.i4.0    
IL_0012:  ldstr       "changed that"
IL_0017:  stelem.ref  
IL_0018:  ret

As you can see, the array is instantiated only once.

JP Alioto
  • 44,864
  • 6
  • 88
  • 112