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

前端 未结 6 446
悲&欢浪女
悲&欢浪女 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:46

    Every reference in C# is pointer to objects on heap as pointer in C++ and ref of C# is same as & in C++

    The reason ref should be avoided is, C# works on fundamental that method should not change the object passed in parameter, because for someone who does not have source of method may not know if it will result in loss of data or not.

    String a = "  A  ";
    String b = a.Trim();
    

    In this case I am confident that a remains intact. In mathematics change should be seen as an assignment that visually tells is that b is changed here by programmer's consent.

    a = a.Trim();
    

    This code will modify a itself and the coder is aware of it.

    To preserve this method of change by assignment ref should be avoided unless it is exceptional case.

提交回复
热议问题