tags:

views:

273

answers:

5

Curious, what happens when you return keyword this from a struct in C#?

For example:

public struct MyStruct 
{
  // ... some constructors and properties 1-3

  public MyStruct Copy()
  {
     return MyStruct(Property1, Property2, Property3);
  }

  // vs

  public MyStruct This()
  {
     return this;
  }
}
+14  A: 

It returns an independent copy of the value. In other words:

MyStruct x = new MyStruct();
y = x;

is like

MyStruct x = new MyStruct();
y = x.This();

It's pretty pointless really.

Bear in mind that "the value" is basically "the bits making up everything to do with the fields in the struct". If those fields are references, the reference values will be copied (not the objects they refer to). If they're other value types, those values will just be copied.


Curious factoid: in structs, you can reassign this:

this = new MyStruct();

Please don't do that though :)

Jon Skeet
A new obfuscation technique! - thanks John ;-)
Dan Diplo
Jon: +1 - That factoid is just evil. Please don't let people know they can pervert their code that way! ;)
Reed Copsey
@Reed: You want to know what's really evil? It even works if your fields are readonly!
Jon Skeet
Kind of like recreating an object in C++ by calling the destructor an the in-place new. And that is even suggested as an idiom in the standard!!!
David Rodríguez - dribeas
+1 just for that evil fact.
Botz3000
+1  A: 

You'll return a by-value copy of the struct. It's basically the same as your Copy routine, provided that Copy actually copies every field in the struct.

This is fairly confusing code, though, so I would avoid it. People will expect a reference type if you're returning "this".

Reed Copsey
A: 

I would never use the word This, (however it is capitalized) for a function name in C#, as this conflicts with the use of the lower case this to represent an indexer property ...

And if you already have a variable which contains an instance of this struct, why on earth would you want to call a method on that variable that effectively cloned a copy of it? You could accomplish the same thing just using the variable itself...

i.e.,

   MyStruct x = new Mystruct();
   MyStruct y = x.This();

is equivilent to just:

   MyStruct x = new Mystruct();
   MyStruct y = x;
Charles Bretana
I'm not using it in real code, just typed it up quick, as I was curious :)
Alex Baranosky
A: 

You would get back a copy of your struct. assign MyStruct.This to another variable, then change it, and look at the original variable, you'll see it hasn't changed.

Botz3000
+1  A: 

As I recall (I've not tried it myself), DataGridComboBox cells in data grids can't bind to the underlying property using SelectedItem; you have to use SelectedValue. Thus, if you want to set the DataSource property to a collection of objects and return a reference to the selected object, you'll have to create a "This" property and use its name as the ValueMember property.

XXXXX