Carven Carven - 2 months ago 11
C# Question

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

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(); = "My Name";
MyClass cls = New MyClass();

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


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();

            Console.WriteLine("Changing Emp Name To xyz");
            someTestObj.Name = "xyz";

            Console.WriteLine("Accessing Assigned Emp Name");