Search code examples
c#classoopreference-type

Change class property value in method


I have following code

public class Myclass
{
    public int someProp{ get; set; };
}
public class Program
{
    public static void Main(string[] args)
    {
        Myclass m = new Myclass();
        Console.WriteLine(m.someProp);
        ChangeValue(m);
        Console.WriteLine(m.someProp);
        SetToNull(m);
        Console.WriteLine(m.someProp);
        Console.ReadKey();
    }
    static void ChangeValue(Myclass m)
    {
        m.someProp = 10;
    }
    static void SetToNull(Myclass m)
    {
        m = null;
    }
}

The result is 0 10 10
I'm wondering why after I set the class to null it shows 10.
Is the m which is pass to the method is a copy of the object or it's just reference.


Solution

  • Is the m which is pass to the method is a copy of the object or it's just reference.

    You are passing a copy of the "m" reference to the methods. If you want to pass the actual reference to the MyClass object in memory you could use the ref keyword:

    public class Program
    {
        public static void Main(string[] args)
        {
            Myclass m = new Myclass();
            SetToNull(ref m);
            if(m == null)
                Console.WriteLine("NULL!");
            Console.ReadKey();
        }
    
        static void SetToNull(ref Myclass m)
        {
            m = null;
        }
    }
    

    Then the SetToNull method will set the actual "m" reference to a null reference.