开发者

Do I need a ref keyword for this method?

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 prope开发者_JAVA技巧rties 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?


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜