0

I want to update one object with the data from another, so something like:

User updatingUser = Users.Get(someId);

updatingUser.Name = otherUser.Name;
updatingUser.Age = otherUser.Age;

Now I want to create a method to perform this update, do I need a ref in the parameter list?

public static void UpdateUserFromUser(User original, User other)
{
  original.Name = other.Name;
  original.Age = other.Age;
  ..
  ..

}

Now the 'original' user passed in has properties on the object that are set, and that will not be updated, so this user object gets SOME properties updated.

I need a ref correct, like:

public static void UpdateUserFromUser(ref User original, User other)

Or will the object 'original' get updated without the need for ref?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

3 Answers3

3

That depends whether User is a struct or a class. Classes are passed by reference, meaning that if User is a class, you don't need the ref keyword to update the original object. Structs are passed by value, which means you need to use ref if you are to update it.

Mark H
  • 13,797
  • 4
  • 31
  • 45
2

If User is a class, there is no need for the ref keyword as classes are reference types. There is actually a subtle difference in behavior if you use ref, but in your case it is not necessary since you are not modifying the variable; rather you are modifying the properties of the object that it refers to.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • @Blankman: `ref` on a reference type allows you to modify which object in memory the variable points to. This explains it succinctly: http://stackoverflow.com/questions/961717/c-what-is-the-use-of-ref-for-reference-type-variables – BoltClock Dec 30 '10 at 17:26
0

The ref isn't required (assuming User is a class).

Iridium
  • 23,323
  • 6
  • 52
  • 74