C# objects by Ref

后端 未结 8 800
清歌不尽
清歌不尽 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:44

    Try reassigning the student object rather than setting properties of it.

    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";
    }
    

    Don't think of ref as "passing by reference" because all reference types are passed by reference. Think of it as "reference to this object can be reassigned"

提交回复
热议问题