Introduction to unsafe code

suggest change

C# allows using pointer variables in a function of code block when it is marked by the unsafe modifier. The unsafe code or the unmanaged code is a code block that uses a pointer variable.

A pointer is a variable whose value is the address of another variable i.e., the direct address of the memory location. similar to any variable or constant, you must declare a pointer before you can use it to store any variable address.

The general form of a pointer declaration is:

type *var-name;

Following are valid pointer declarations:

int    *ip;    /* pointer to an integer */
double *dp;    /* pointer to a double */
float  *fp;    /* pointer to a float */
char   *ch     /* pointer to a character */

The following example illustrates use of pointers in C#, using the unsafe modifier:

using System;
namespace UnsafeCodeApplication
{
   class Program
   {
      static unsafe void Main(string[] args)
      {
         int var = 20;
         int* p = &var;
         Console.WriteLine("Data is: {0} ",  var);
         Console.WriteLine("Address is: {0}",  (int)p);
         Console.ReadKey();
      }
   }
}

When the above code wass compiled and executed, it produces the following result:

Data is: 20
Address is: 99215364

Instead of declaring an entire method as unsafe, you can also declare a part of the code as unsafe:

// safe code
unsafe
{
    // you can use pointers here
}
// safe code

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Pointers and Unsafe Code:
* Introduction to unsafe code

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
136 Pointers and Unsafe Code
147 C# Script