Skip to content

I understand passing by reference like this, when use ref keyword, is right? #9111

Closed
@CwjXFH

Description

@CwjXFH

init:

var array = new string[] {"csharp","java","python","go"};
var value = array[0];
ref var refValue = ref array[0];

image

modify value, it will point another object and doesn't effect the original array

value = "dotnet";

image

modify refValue, it point a new object and will change the original array element's value

refValue = "dotnet";

image


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Activity

BillWagner

BillWagner commented on Nov 30, 2018

@BillWagner
Member

Your understanding is correct @CwjXFH

Closing as the doc is correct.

FrankHileman

FrankHileman commented on Apr 21, 2020

@FrankHileman

I would like to see an example using a struct as well.

CwjXFH

CwjXFH commented on Apr 22, 2020

@CwjXFH
Author

@FrankHileman

Maybe this example will help you, in the picture below, refValue passed by ref, has the same address and value with num; argument value passed by value, it just has the same value with num, the address is different.

And recommended that you read the following document:

Passing Parameters (C# Programming Guide)
Method Parameters (C# Reference)
The address-of operator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @BillWagner@dotnet-bot@CwjXFH@mairaw@FrankHileman

        Issue actions

          I understand passing by reference like this, when use ref keyword, is right? · Issue #9111 · dotnet/docs