C# objects by Ref

后端 未结 8 796
清歌不尽
清歌不尽 2021-01-27 12:23

If one passes an object to a method using the \'Ref\' keyword then what is the difference with passing it without the ref keyword?

Because both yield the same result, th

相关标签:
8条回答
  • 2021-01-27 12:56

    Try changing your two Student methods to:

    public static void SetStudent( ref Student student )
    {
        student = new Student();
        student.Age = 16;
        student.Name = "StudentY";
    }
    
    public static void AnotherStudent( Student studenta )
    {
        studenta = new Student();
        studenta.Age = 12;
        studenta.Name = "StudentX";
    }
    

    The call to SetStudent will now change your static student variable to reference a new instance because it is passed as a ref. The call to AnotherStudent won't change the reference.

    0 讨论(0)
  • 2021-01-27 12:58

    Passing by reference allows the method to change the value of the argument passed to the method - so for a reference type, that allows it to change a variable's value to refer to a different object. Here's an example:

    using System;
    using System.Text;
    
    class Test    
    {    
        static void PassByValue(StringBuilder x)
        {
            x.Append(" - Modified object in method");
            x = new StringBuilder("New StringBuilder object");
        }
    
        static void PassByReference(ref StringBuilder x)
        {
            x.Append(" - Modified object in method");
            x = new StringBuilder("New StringBuilder object");
        }
    
        static void Main()
        {
            StringBuilder builder = new StringBuilder("Original");
            PassByValue(builder);
            Console.WriteLine(builder);
    
            builder = new StringBuilder("Original");
            PassByReference(ref builder);
            Console.WriteLine(builder);
        }
    }
    

    In both cases, the original StringBuilder has its contents modified, and then the parameter is assigned a new value. In the "pass by value" case, this doesn't change the value of the builder variable in Main. In the "pass by reference" case, the value of builder refers to the new StringBuilder, so the results are:

    Original - Modified object in method
    New StringBuilder object
    

    In your case, you're not seeing any difference with or without ref because you're not changing the value of the parameter itself - only the data in the object it refers to.

    For more information, see my article on parameter passing.

    0 讨论(0)
提交回复
热议问题