In this article, I am going to share information about Pointers in C#:
Pointers in C#
A pointer is simply a variable whose value is the address of another variable. We can not use pointers directly. To use a pointer, we need to have a specific block for it. The 'unsafe' keyword defines the scope to use pointer variables. Pointer variables can only be used inside an unsafe code block.
The syntax of a pointer variable is shown below.
datatype *<Variable_Name>;
datatype *<Variable_Name>;
For example,
- int* a; // 'a' is a pointer to an Integer
- char* b; // 'b' is a pointer to an Char
- float* c; // 'c' is a pointer to an Float
Uses of pointers
- When interacting with unmanaged APIs or code
- When we have to make communication between two application using IPC
A method with unsafe keyword:
- using System;
- namespace Tutpoint
- {
- class Program
- {
- static unsafe void Main(string[] args)
- {
- // variable 'p' of int type is initialised with value 100
- int p = 100;
- // pointer variable 'q' contains the address of variable 'p' and, '&' used to obtain address of a variable
- int* q = &p;
- Console.WriteLine("Value: " + p);
- Console.WriteLine("Address: " + (int)q);
- Console.ReadKey();
- }
- }
- }
Output
Value: 100
Value: 100
Address: 122743464
If we don't want to use the unsafe keyword on method definition, then there is another option through which we can use pointer variables inside a method. Have a look at the below example.
- using System;
- namespace Tutpoint
- {
- class TutLovers
- {
- public void Program()
- {
- int z = 50;
- Console.WriteLine("Before unsafe code block");
- unsafe
- {
- // variable 'p' of int type is initialised with value 100
- int p = 100;
- // pointer variable 'q' contains the address of variable 'p'
- int* q = &p;
- // pointer variable 'r' contains the address of variable 'z'
- int* r = &z;
- }
- Console.WriteLine("After unsafe code block");
- // This will show an error because pointer variable 's' is used outside unsafe block
- // Error as "pointers and fixed size buffers may only be used in an unsafe context"
- int* s = &z;
- }
- }
- }

Laxmidhar SahooPosted Nov 25, 2017, 4:38 AM
Using of unsafe key and block liked