-1

Please look at the following code-

public class Program
{

  public static void Main()
  {
    A ob = new A();
    ob.x = 120;
    ob.Name = "No";
    GO(ob);
    Console.WriteLine(ob.x);
  }

  public static void GO(A obj)
  {
    obj.x = 50;
    obj.Name = "Local";
    obj = null;
  }
}

in console It prints the value of x 50. but when I am using ref keyword it is giving null reference exception. My question is if object is reference type it should give null reference exception even if I don't use ref. and if it is not then value of x in console should be 120. I am unable to understand this behavior. Please explain whats happening here when we use ref and when we don't.

Vivek Mishra
  • 1,772
  • 1
  • 17
  • 37

1 Answers1

1

When you pass an argument to a method with ref keyword, whatever actions you perform inside the method they are reflected back to the actual argument. In method GO you are setting the argument as null. So object ob has value null before Console.WriteLine, hence the null reference exception.

Also in the opposite case when you call the method without the ref keyword a copy of reference stored in ob variable is passed to obj parameter of the method. So both ob and obj which are two different variables in program stack point to same memory location in the heap. That's how you are able to modify value of x inside the method. But setting the value of obj to null doesn't change the value of ob. Thus no null reference exception here.

Akshey Bhat
  • 8,227
  • 1
  • 20
  • 20
  • you are correct but object is passed as a reference even without using ref that's why value of x changed to 50. but object value didn't set to null and console printed 50 not 120. Why?? – Vivek Mishra Sep 03 '17 at 05:13
  • Check modified answer – Akshey Bhat Sep 03 '17 at 05:19
  • Thanks for the answer.. I also got a better reference for this-https://stackoverflow.com/questions/186891/why-use-the-ref-keyword-when-passing-an-object – Vivek Mishra Sep 03 '17 at 05:28