0

What is the difference between obj.i and reference int k? They point to same address. Which one is better and why?

namespace ConsoleApplication1
{
class pro
{
    public void met1(ref int k,Program obj)
    {      
        obj.i = 30;
        k = 20;
    }
}

class Program
{
    public int i=10;
    static void Main(string[] args)
    { 
        Program pi = new Program();
        pro p = new pro();
        p.met1(ref pi.i, pi);
        Console.WriteLine(pi.i);
        Console.ReadKey();
    }
}
}
BSMP
  • 4,596
  • 8
  • 33
  • 44
karthik sonu
  • 23
  • 1
  • 4
  • 1
    What research have you done? [ask] –  Dec 29 '17 at 05:36
  • There are lots of resources available to explain the difference between passing by value (the default) and passing by reference (when you use `ref` or `out`). See e.g. marked duplicate. In your scenario, if you are okay with `met1()` having access to the entire object, and/or it makes sense for that method to require that entire object, passing the object reference by value is appropriate. If on the other hand you need to modify the `i` field but there's no need for `met1()` to have any of the rest of the object, passing by reference would be appropriate. – Peter Duniho Dec 29 '17 at 05:38
  • Of course, if you don't need to modify the value and don't need the whole object, then you can just pass the _value_ of `i` by value. – Peter Duniho Dec 29 '17 at 05:39
  • @MickyD: feel free to offer a duplicate target you think is better. There are plenty of "passing by reference" questions to choose from. – Peter Duniho Dec 29 '17 at 05:48
  • @PeterDuniho thanks Peter for the additional duplicate links. They are jolly good –  Dec 29 '17 at 11:14

0 Answers0