locked
What's the difference between sending a class object by using ref or simply into a function RRS feed

  • Question

  • User547991737 posted

    My Question is what's the difference between sending a class object by using ref or simply into a function.

    as we know the class is a reference type.

    MyClass c1 = new MyClass();
    f1(c1);
    f2(ref c1);

    Private void f1(MyClass c1 ){
    c1.Name="AAA";
    }

    Private void f2(ref MyClass c1 ){
    c1.Name="AAA";
    }

    Monday, July 3, 2017 5:42 AM

All replies

  • User991499041 posted

    Hi arry.net,

    A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block. To do that, pass the parameter using the ref keyword. For simplicity, the following examples use ref.

    Passing Reference Types by Value

    class Program
    {
    	static void Main(string[] args)
    	{
    		MyClass c1 = new MyClass();
    		c1 = new MyClass { Name = "AAA" };
    		f1(c1);
    		Console.WriteLine(c1.Name);
    
    	}
    
    	static void f1(MyClass c1)
    	{
    		c1 = new MyClass { Name = "BBB" };
    		c1.Name = "CCC";
    		Console.WriteLine(c1.Name);
    	}
    
    	static void f2(ref MyClass c1)
    	{
    		c1 = new MyClass { Name = "BBB" };
    		c1.Name = "CCC";
    		Console.WriteLine(c1.Name);
    	}
    }
    
    class MyClass
    {
    	public string Name { get; set; }
    }
    
    
    /* Output:
       CCC
       AAA
    */

    Passing Reference Types by Reference

    class Program
    {
    	static void Main(string[] args)
    	{
    		MyClass c1 = new MyClass();
    		c1 = new MyClass { Name = "AAA" };
    		f2(ref c1);
    		Console.WriteLine(c1.Name);
    
    	}
    
    	static void f1(MyClass c1)
    	{
    		c1 = new MyClass { Name = "BBB" };
    		c1.Name = "CCC";
    		Console.WriteLine(c1.Name);
    	}
    
    	static void f2(ref MyClass c1)
    	{
    		c1 = new MyClass { Name = "BBB" };
    		c1.Name = "CCC";
    		Console.WriteLine(c1.Name);
    	}
    }
    
    class MyClass
    {
    	public string Name { get; set; }
    }
    
    
    /* Output:
       CCC
       CCC
    */

    Regards,

    zxj

    Monday, July 3, 2017 6:38 AM