Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Boron_the_Moron
Apr 28, 2013
This might be a dumb question, but I need clarification.

In C#, let's say I make a class called "Test", and give it an int variable. I then make a Test object, and store it in a Test object variable. I then create two more Test object variables, and assign the original Test object to both. If I change the value of the int variable in either of the two new objects, will those changes propagate backwards to the original object?

My brief test says yes, but I'm not sure if that's a consistent behaviour I can take advantage of, or if I've walked into some weird edge case that I can't rely on. If it is consistent, how would I go about splitting a copied object into its own unique object? Would I need to create a new object, and copy the values over? Or is there a way to directly make an object variable unique, and untied to anything else?

Adbot
ADBOT LOVES YOU

Boron_the_Moron
Apr 28, 2013

nielsm posted:

You probably want the .NET thread, not the C and C++ thread, for C# questions, but anyway:

In C# you have two kinds of object-like user-defined types: Class and Struct. The syntax for declaring either is basically the same, the only difference is whether you use the "class" or the "struct" keyword at the beginning.
A variable of a C# class type is a reference type (pointer-like), it references an object that lives somewhere else in memory. Assigning the value of one class type variable to another class type variable only copies the reference, both variables now reference the same object. You have two variables, but a single object.
Meanwhile in C#, a variable of a struct type is a value, it is the object. Assigning one struct type variable to another creates a full copy of the object, so you have two separate objects, one contained in each variable.

Ah, thank you.

I know this is the wrong thread, but would I be right in thinking that in order to split an object variable into its own unique object, I would need to use the "new" keyword, and copy the values of the original object into the new one?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply