Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object passed as parameter to another class, by value or reference?

Tags:

In C#, I know that by default, any parameters passed into a function would be by copy, that's, within the function, there is a local copy of the parameter. But, what about when an object is passed as parameter to another class?

Would a scenario like the following one be passed by reference or by value:

class MyClass {
   private Object localObj;

   public void SetObject(Object obj) {
      localObj = obj;
   }
}

void Main() {
   Object someTestObj = new Object();
   someTestObj.name = "My Name";
   MyClass cls = New MyClass();
   cls.SetObject(someTesetObj);
}

In this case, would the class variable localObj be having the same copy as the someTestObj created in the Main driver class? Or would the two variables be pointing to a different object instance?

like image 375
Carven Avatar asked Oct 21 '12 12:10

Carven


1 Answers

"Objects" are NEVER passed in C# -- "objects" are not values in the language. The only types in the language are primitive types, struct types, etc. and reference types. No "object types".

The types Object, MyClass, etc. are reference types. Their values are "references" -- pointers to objects. Objects can only be manipulated through references -- when you do new on them, you get a reference, the . operator operates on a reference; etc. There is no way to get a variable whose value "is" an object, because there are no object types.

All types, including reference types, can be passed by value or by reference. A parameter is passed by reference if it has a keyword like ref or out. The SetObject method's obj parameter (which is of a reference type) does not have such a keyword, so it is passed by value -- the reference is passed by value.

like image 164
newacct Avatar answered Oct 06 '22 00:10

newacct