-4

As we know passing object to any method is reference type. Then what is the difference between passing simply object and passing object with ref keyword in a method? Please reply with proper explanation.

2 Answers2

0

When you don't pass an object with ref keyword then object reference is passed by value. Whereas, in other case object is passed by reference. You can get better explanation with following example.

Example:

private void button1_Click_2(object sender, EventArgs e)
        {

        Student s = new Student
            {
                FirstName = "Svetlana",
                LastName = "Omelchenko",
                Password = "hh",
                modules = new string[] { "001", "002", "003", "004" }
            };
        SomeMethod(s);

        Console.WriteLine(s.FirstName); //will output Svetlana

    }


    private void SomeMethod(Student s)
    {
        s = new Student();
        s.FirstName = "New instance";
    }
    class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Password { get; set; }
        public string[] modules { get; set; }
    }

now if you have that method like this

private void SomeMethod(ref Student s)
        {
            s = new Student();
            s.FirstName = "New instance";
        }

then output will be New instance

Ehsan
  • 31,833
  • 6
  • 56
  • 65
0

This has been asked many times. With SomeMethod(object obj) the reference is passed by value. So the reference is copied by value and given to the method. The object itself is not copied. The two references "point to" the same object.

With SomeMethod(ref object obj) the reference type is passed by reference. So the method uses the same reference to the object (not another reference to the same object as in by-value).

The difference will be clear if the SomeMethod code assigns to the obj parameter, for example

obj = "CHANGED!";

Then after the method returns, whether the caller sees that the references has a new value or not, depends on whether ref was used or not.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181