1

Just curious on some theory

I have a C programming background and if you were to pass structs across functions you'd most likely pass a pointer to the struct

Wondering, in C#, if I am passing a data object, such as an entity model, is there any benefit of passing it by reference? Behind the scenes is it passing a pointer or is there more to it?

In reality my models are fairly small so if there are any speed or performance increases I doubt that it would be noticeable but I figured it would be good to know

Kirk Broadhurst
  • 27,836
  • 16
  • 104
  • 169
Russell
  • 21
  • 4
  • By default objects are passed by reference. A method can change the state of the object, but it will still be the same object when the method returns. With `ref`, your variable may reference an entirely different object after the method returns. I have never had to use `ref`, and I have only ever seen it used incorrectly. – JosephHirn Feb 07 '13 at 04:47

1 Answers1

1

Behind the scenes is it passing a pointer or is there more to it?

Essentially, yes. All reference types (basically everything except native types and structs) are passed by reference (technically they are passed by value but in this case the value is a reference). If you pass a model into a function that change the values of the model, those changes will be seen by the calling function.

if I am passing a data object, such as an entity model, is there any benefit of passing it by reference?

probably not. In that case you'd be passing a reference by reference (analogous to a pointer to a pointer). I have never seen a case where you pass in a model reference to a function and expect that function to update the reference. You see that done with return types and occasionally out parameters instead.

D Stanley
  • 149,601
  • 11
  • 178
  • 240