Object passed as parameter to another class, by value or reference?
Objects will be passed by reference irrespective of within methods of same class or another class. Here is a modified version of same sample code to help you understand. The value will be changed to 'xyz.'
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Employee
{
public string Name { get; set; }
}
public class MyClass
{
public Employee EmpObj;
public void SetObject(Employee obj)
{
EmpObj = obj;
}
}
public class Program
{
static void Main(string[] args)
{
Employee someTestObj = new Employee();
someTestObj.Name = "ABC";
MyClass cls = new MyClass();
cls.SetObject(someTestObj);
Console.WriteLine("Changing Emp Name To xyz");
someTestObj.Name = "xyz";
Console.WriteLine("Accessing Assigned Emp Name");
Console.WriteLine(cls.EmpObj.Name);
Console.ReadLine();
}
}
}
"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.