5

Quick question. (I was not able to find documentation about this anywhere)

When you do this:

Texture2D t1;
t1 = content.Load<Texture2D>("some texture");

Texture2D t2;
t2 = t1;

Does it creates a reference or actually copies the texture?

I would like to know it so I can take it into account when implementing related stuff.

NewProger
  • 2,945
  • 9
  • 40
  • 58

2 Answers2

5

Texture2D is a class. Hence, assignment will create a copy of the reference - t1 and t2 will have referential equality, ie Object.ReferenceEquals(t1, t2) will be true.

Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
  • 1
    I see. Thank you. The reasoun I wasn't sure is because it behaves slightly different than other classes. But I guess that is just nuances. – NewProger Sep 17 '12 at 16:54
  • 1
    What you need to always keep in mind is: is the type a reference type ("class") or value type ("struct"). Value types create copies on assignment. Reference types don't. – Dave Doknjas Sep 17 '12 at 16:59
  • 1
    Hm. You are right, and it's pretty logical. I guess I should have used my brain before asking that question... But I didn't know about that "Object.ReferenceEquals" so I learned something new which is always good. – NewProger Sep 17 '12 at 17:03
4

It's only a reference assignment. No actual data is moved around.

Tudor
  • 61,523
  • 12
  • 102
  • 142
  • Oh, that's good. But just to make sure: then I can freely pass it around through multiple function calls and don't worry about it creatind unneded copies multiple times and consuming resources? – NewProger Sep 17 '12 at 16:51
  • @NewProger: Exactly. Only references get passed around. Be careful though because this also means that changing members will be reflected in the calling code. – Tudor Sep 17 '12 at 16:52