Alex Baranosky
Alex Baranosky

Reputation: 50064

What happens when you return "this" from a struct in C#?

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;
  }
}

Upvotes: 3

Views: 1178

Answers (5)

XXXXX
XXXXX

Reputation: 1096

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.

Upvotes: 1

Botz3000
Botz3000

Reputation: 39610

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.

Upvotes: 0

Charles Bretana
Charles Bretana

Reputation: 146499

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; 

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564413

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".

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500615

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 :)

Upvotes: 16

Related Questions