tags:

views:

389

answers:

9

Hi,

I want to know if pointers exist in .NET technology. If yes, is there any example for pointers in C#?

Please guide me .

+13  A: 

Yes, they do exist...

And an example of their use...

LukeH
+2  A: 

Yes they exist. You can write unsafe code.

Darin Dimitrov
+5  A: 

Yes, they do exist.

Check out the documentation:

And these SO questions:

And a little introduction to unsafe code:

Bertrand Marron
+2  A: 

Yes, they are but only in a limited fashion, have a look at this article on MSDN

Lazarus
+2  A: 

Yes they do. You can start with this link.

Fernando
+2  A: 

Yes you can use pointers if you do unsafe code. See this MSDN section for details: Unsafe Code and Pointers (C# Programming Guide)

ho1
+2  A: 

Hai, pointers we can use in .net but the framework not support pointers because of automatic garbage collection. So we write as un managed code .For use unmanaged code go to your project properties->build -> and enable allow unsafe code.

sample:

 class UnsafeCode
{
    //mark main as unsafe
    unsafe public static void Main()
    {
        int count = 99;
        int* pointer;   //create an int pointer. 
        pointer = &count;   //put address of count into pointer

        Console.WriteLine( "Initial value of count is " + *pointer );
        *pointer = 10;  //assign 10 to count via pointer
        Console.WriteLine( "New value of count is " + *pointer);
        Console.ReadLine();
       }
}
Vyas
+5  A: 

Yes, pointers exist.

References are actually pointers, but they are special in the way that the garbage collector knows about them and changes them when it moves objects around.

Pointers can be used in unsafe code, but then you have to make sure that the garbage collector doesn't move things around that you are pointing at.

Example:

string x = "asdf";
unsafe {
  fixed (char* s = x) {
    char* p = s;
    for (int i = 0; i < 4; i++) {
      Console.WriteLine(*p);
      p++;
    }
  }
}

Note that a managed object that you want to access via a pointer has to be protected from being moved by using the fixed command, and that the compiler won't let you change the pointer that you get, so if you want a changeable pointer you have to copy it.

You need to enable unsafe code in your project settings to use the unsafe keyword.

Guffa
+2  A: 

I would take a long, hard look at what you intend to do and see if you are trying to write C++ code in C#. There are very few instances where unsafe code is the preferred solution. C# abstracts at a higher level than C++. As such, you might want to consider following the idioms of the language you are using.

Andy_Vulhop