Pages

Friday, September 16, 2011

When we should use REF keyword to pass a reference type argument?

If a value type (ex: int) is passed to a method, by default a copy of the value is being passed as argument and any change applied to that variable will not be applied to the original variable. If you want those changes to be there in original variable, you need to pass the argument using REF keyword.

Any programmer would be familiar with this scenario.

Do we need to pass a reference type argument to a method using REF keyword?

It depends on the type of change you are willing to do in your method.

If we only want to change the state of the object the REF keyword is not required.
But if you want to assign a new value to the variable in method and if it should represent in original variable, you should use REF keyword.

Why?

In C#, everytihng is passed by value. Even if it is a reference type, copy of the reference is passed to the variable by default. However, if you use REF keyword, the original reference will be passed to the method, thus representing all the changes you do in the method variable in the original variable.

Example:

public class Student
      int ID {get; set;}

Student stud1 = new Student(1);

// Assign a new object (Stud2) with ID = 2 - assign object to a new object

changeObjectByVal ( stud1);  // stud1 ID value remains as 1
changeObjectByRef ( ref stud1);  // stud1 ID value will be 2

// Change ID value to 3 - changing the object's state

changeObjectAttrByVal (stud1);  //  stud1 ID value will be 3
changeObjectAttrByRef (stud1);  //  stud1 ID value will be 3

No comments:

Post a Comment