What is the difference between a C# Reference and a Pointer?

后端 未结 10 1901
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 21:45

I do not quite understand the difference between a C# reference and a pointer. They both point to a place in memory don\'t they? The only difference I can figure out is that

10条回答
  •  天命终不由人
    2020-11-28 22:30

    I think it's important for developers to understand the concept of a pointer—that is, to understand indirection. That doesn't mean they necessarily have to use pointers. It's also important to understand that the concept of a reference differs from the concept of pointer, although only subtly, but that the implementation of a reference almost always is a pointer.

    That is to say, a variable holding a reference is just a pointer-sized block of memory holding a pointer to the object. However, this variable cannot be used in the same way that a pointer variable can be used. In C# (and C, and C++, ...), a pointer can be indexed like an array, but a reference cannot. In C#, a reference is tracked by the garbage collector, a pointer cannot be. In C++, a pointer can be reassigned, a reference cannot. Syntactically and semantically, pointers and references are quite different, but mechanically, they're the same.

提交回复
热议问题