C# ref is it like a pointer in C/C++ or a reference in C++?

前端 未结 6 457
悲&欢浪女
悲&欢浪女 2021-01-30 00:10

I\'m working with the ref and don\'t understand clearly \"Is it like a pointer as in C/C++ or it\'s like a reference in C++?\"

Why did I ask such a

6条回答
  •  不知归路
    2021-01-30 00:40

    A ref in C# is equivalent to a C++ reference:

    • Their intent is pass-by-reference
    • There are no null references
    • There are no uninitialized references
    • You cannot rebind references
    • When you spell the reference, you are actually denoting the referred variable

    Some C++ code:

    void foo(int& x)
    {
        x = 42;
    }
    // ...
    int answer = 0;
    foo(answer);
    

    Equivalent C# code:

    void foo(ref int x)
    {
        x = 42;
    }
    // ...
    int answer = 0;
    foo(ref answer);
    

提交回复
热议问题