Skip to content

Do we have use of pointer in C# if so how

Shiladitya

Asked Feb 1, 2006, 8:10 PM EST3 answers
Share
LinkedInX
Hello friends
this is softy.

I am a C# developer, a number of times I have come across the question that is C# more advantage than C++ and do we have use of pointers in C# ?
Please let me know if you have the answers.
Thanks

3 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    You can use the "ref" keywork to use references. That's not exactly the same thing as pointers, but as I know it's the closest form that C# allows.
    Simon
    0
  • 0
    Hihi ;) It's my understanding that EVERYTHING is a pointer by default in C#. if you don't believe me, write yourself a simple linked list in C#. public class node { int info; node next; } public class LinkedList { public LinkedList(int in) { First.info = in; } node First; public AddNode(int in) { First.next = new node(); First.next.info = in; } } Something like that should do a basic add for a simple linked list, it's been awhile since I did a linked list, so excuse my wrong code if this doesn't work, but I hope you get the idea. in a linked list the nodes would have to be explicitly created as pointers in C++, but here they are by default, so no need to be explicit.
    0
  • 0
    >>It's my understanding that EVERYTHING is a pointer by default in C#
    Classes are reference types, and in .NET a reference stands for a "managed pointer". Garbage collector has information about object references in stack memory, and uses them to keep alive or delete objects located in heap memory.

    Structs however (and all other value types), are not reference types, and they got no managed pointer in similar meaning. Value types are located directly in stack memory, and CRL deletes them from there.

    >>You can use the "ref" keywork to use references. That's not exactly the same thing as pointers, but as I know it's the closest form that C# allows.
    Thats not quite true. You can indeed override the garbage colletion mechanism, and use POINTERS directly in your C# program. The pointers have similar syntax than in C++, *, & and so on. You must wrap pointer handling code inside the unsafe block. But pointers are seldom if never needed in C# programs, since using pointers does wreck the whole idea of safe and automatic garbage collection, don't you think?

    I myself would not recommend the direct use of pointers in C#. Only situations when you ever would need them, would be the use of C-generic dll's and hard-core code optimization. Optimization with pointers still requires you yourself to handle the memory management! Writing a good code without pointers and with good algorithms is better than risky unmanaged memory. Managed code indeed stands for that someone (CLR) manages the memory for you.
    0