find a location for property in a new city

Wednesday, 7 December 2016

Reference object with ref keyword on a method. What's the point?

I wondered the other day what the point is in making a method parameter a ref when it is already a reference type. After playing around for a bit I came up with some concise code to illustrate the difference.

The difference is that, although you can modify the reference object that was passed in with both methods. Changing the reference entirely (i.e. pointing to a different object) only has an effect outside the scope of the method if the object was passed through with the ref keyword.

This code should explain better than English:

void Main()
{
 var t1 = new Thing();
 Test(t1);
 t1.Write(); // Chair
 
 var t2 = new Thing();
 Test(ref t2);
 t2.Write(); // Table
}

void Test(Thing t)
{
 t.Name = "Chair";
 t = new Thing { Name = "Table" };
}

void Test(ref Thing t)
{
 t.Name = "Chair";
 t = new Thing { Name = "Table" };
}

class Thing
{
 public string Name { get; set; }
 public void Write() => Console.WriteLine(Name);
}

Follow britishdev on Twitter

8 comments:

  1. I understand what you bring it very meaningful and useful, thanks


    mario | free mahjong  |   atari breakout

    ReplyDelete
  2. Informative post! I really amazed to see the great information that you have shared with us. I want to get more updates to increase my knowledge. Keep doing the great work up. trustable plumbers dallas

    ReplyDelete
  3. Your blog posts are more interesting and impressive. I think there are many people like and visit it regularly, including me.I actually appreciate your own position and I will be sure to come back here. five nights at freddy’s 4 | word cookies answers | hotmail sign in | hill climb racing 2

    ReplyDelete
  4. Thank you for this valuable information. The information you shared is very interesting. Brave Technologies is an leading erp software development company in chennai.
    enterprise resource planning chennai | web development company in chennai

    ReplyDelete
  5. This is one of the cult game now, a lot of people enjoy playing them . Also you can refer to the game :
    animal jam 2 | five nights at freddys 2 | hotmail login

    ReplyDelete
  6. This is a wonderful post. I enjoyed the information lot. I will bookmark this page. Thanks for sharing this information.
    starfall | barney | abcya

    ReplyDelete
  7. Thanks for sharing.for more information : click here

    ReplyDelete