2

Suppose I have this code:

struct Normal
{
    public float x;
    public float y;
}

class NormalContainer
{
   public Normal[] Normals
   {
       get; set;
   }
}

class Main
{
     void Run( NormalContainer container )
     {
         Normal[] normals = container.Normals // 1 - see below
         normals[5].x = 4;                    // 3 - see below
         container.Normals = normals;         // 2 - see below
     }
}

Does (1) create a copy of the array or is this a reference to the memory occupied by the array? What about (2) ?

Thanks

1
  • This would be an excellent time to fire up the debugger and trace those statements - you can then see if the code makes any difference to what's inside the passed object or not. Commented Mar 14, 2012 at 16:01

3 Answers 3

3

Array is a reference type, so you are just copying the reference to the array instance.

Sign up to request clarification or add additional context in comments.

Comments

2

An array in C# is a reference type. Items like assignment create copies of the reference vs. the value. At the end of (1) you end up with a local reference to the array stored in container

Note: In C# it's more proper to say "reference to the object" vs. "reference to the memory"

Comments

1

(1) copies the array's reference

(2) same

Array variables are reference types, regardless of their underlying element type, so whenever you assign an array variable to another, you are just copying the reference.

2 Comments

So what happens on (3) ? If the array is a reference then if I do normals[5].x = 4 does that change the value in container.Normals before line (2) ? And if yes then line (2) is unnecessary correct?
Nevermind I sat down and wrote my example... This is exactly what happens.. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.