(Texture2D) t1 = t2; Does it creates reference or a copy?
Asked Answered
T

2

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.

Trinitrocresol answered 17/9, 2012 at 16:48 Comment(0)
D
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.

Deenadeenya answered 17/9, 2012 at 16:50 Comment(3)
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.Trinitrocresol
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.Gentle
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.Trinitrocresol
M
4

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

Mannish answered 17/9, 2012 at 16:49 Comment(2)
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?Trinitrocresol
@NewProger: Exactly. Only references get passed around. Be careful though because this also means that changing members will be reflected in the calling code.Mannish

© 2022 - 2024 — McMap. All rights reserved.