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

前端 未结 6 447
悲&欢浪女
悲&欢浪女 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 01:03

    C# has no equvalent of C++ pointers and works on references. ref adds a level of indirection. It makes value type argument a reference and when used with reference type it makes it a reference to a reference.

    In short it allows to carry any changes to a value type outside a method call. For reference type it allows to replace the original reference to a totally different object (and not just change object content). It can be used if you want to re-initialize an object inside a method and the only way to do it is to recreate it. Although I would try avoid such an approach.

    So to answer your question ref would be like C++ reference to a reference.

    EDIT

    The above is true for safe code. Pointers do exist in unsafe C# and are used in some very specific cases.

提交回复
热议问题