After asking this question , I still have a question.
I got both excellent answers but I’m still having a trouble finding how could this actually be occur: ( how could a fault situation can occur) :
I will start with an example :
public void Do(string [] g)
{
g=null; //<========
}
void Main()
{
var t=new string[3];
t[0]="1"; t[1]="1"; t[2]="1";
Do( t);
Console.WriteLine ( t.Length);
}
the notated line can be execute in a different thread but each thread has its own g variable !
(and please remember that I can’t add items to an arrray. cause array length is created at creation)
No matter what will I do with the function Do – (no matter in what thread) , the Console.Writeline result will always be 3 ( unless using ref).
so lets see the real code :
public static string Concat(params string[] values)
#1 {
#2 if (values == null)
#3 {
#4 throw new ArgumentNullException("values");
#5 }
#6 int totalLength = 0;
#7 string[] strArray = new string[values.Length];
#8 for (int i = 0; i < values.Length; i++)
#9 {
#10 string str = values[i];
#11 strArray[i] = (str == null) ? Empty : str;
#12 totalLength += strArray[i].Length;
#13 if (totalLength < 0)
#14 {
#15 throw new OutOfMemoryException();
#16 }
#17 }
#18 return ConcatArray(strArray, totalLength);
#19 }
My saying is : once I’m on #1 , in thread X , this thread will forever will have array with length 3.
If another thread wants to destroy/change the array length ( which I cant understand how , cause the array has fixed length , all he can do is making it null) – it will have a different copy of pointer address.
I must be missing something here.
-
What am I missing ?
-
what is the code which other thread could execute which will cause an error ?(assuming we don’t copy the array).
Without the intermediate array there would be a race condition, the Thread could change
data[0]after its length was added tototalLengthbut before the (presumably unsafe) call toConcatArray(). The low-level method would then copy 5 chars to a buffer of size 3.