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?
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With