x


Returning a copy of a struct - c#

Hi,

I have a script that manages different types of tiles, all info of a tile is grouped together in a struct "TileInfo". Now I have a method:

public static TileInfo GetTileInfo(int id)
{
return TileInfoList.GetTileInfo(id);
//Looks up the TileInfo var with ID == id and returns the correct struct
}

Now my question, will this return a copy of that struct, or the actual struct itself ? So when I use this method, and change the returned struct, will the original change ? If so, how do I return a copy so my original struct stays the way he was ? If not, just out of curiosity, how do I make it so it returns the actual struct ? :P (I need it to return a copy, but it's still interesting :P)

(I'm not sure if I'm saying it right "returning the actual struct", or is there a word for an instance of that struct (like "object" when we're talking about classes) or is it also just called an "object" ? :D)

Thanks !

-Pablo

more ▼

asked Apr 08, 2011 at 11:48 AM

The Oddler gravatar image

The Oddler
345 103 84 97

You want to return an object reference on constructor call?

Apr 08, 2011 at 12:13 PM Proclyon
(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

structs are value types. As such the function will return a copy of that struct and NOT the actual struct itself.

See http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx for more info.

more ▼

answered Apr 08, 2011 at 01:31 PM

Chewbacca gravatar image

Chewbacca
51 4

Thanks ! Perfect answer :P

Apr 08, 2011 at 01:55 PM The Oddler
(comments are locked)
10|3000 characters needed characters left

Structs are always copied, classes are always referenced

more ▼

answered Apr 08, 2011 at 01:45 PM

Dani gravatar image

Dani
198 47 38 52

Thanks :D Pity for you Chewbacca was first, and apparently I can only select one answer as the correct one :(

Apr 08, 2011 at 01:56 PM The Oddler
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1679
x554
x70
x5

asked: Apr 08, 2011 at 11:48 AM

Seen: 3031 times

Last Updated: Apr 08, 2011 at 11:48 AM