I have an object that I need updated data from in every update in a game loop (in C#). Is it better to pass-by-reference the object into the constructor of the object that performs the update loop so that the reference constantly has the up-to-date object,
or should I pass it normally as a parameter into the Update method (which is called every update)?
So this as a constructor:
public UpdatingObject(ref DataObject dataObject)
or this as an update loop header (passed-by-value as default):
public void Update(DataObject dataObject)
Pass by reference when you need to, i.e., when you need to reassign the reference to refer to a different object:
If the method guarantees to set
othen pass it as anoutparameter.The default semantics (pass by copy of reference) are suitable for most needs as you typically only modify fields/properties on an object.
If the argument is a value type then you would need to use
refto mutate the argument in a way that the caller would see.My question is; why are you mutating an argument to a constructor? It seem a bit odd to me.