Can we use pointers in C# ?

Can we use pointers in .Net Framework c# vb.net

What is a pointer ?

A pointer is a variable that stores a memory address. Every variable declared in a program has two components:

  1. Address of a variable
  2. Value stored in the variable

Pointer declarations use the * operator.

typeName * variableName;

E.g.

int i; // declaration of a variable i int *ptr; // declaration of a pointer, called ptr

Is there pointer in C# like C or C++ ?

Is there pointer in .Net Framework  like C or C++ ? c# vb.net

One of the biggest advantages of the .NET platform is the support for type safety. To maintain type safety and security, use of pointers is rarely required in C#. But, there are some situations that require them.

By using the unsafe keyword, you can define an unsafe context in which pointers can be used in .Net platform. Using an unsafe context to allow pointers is warranted by the following cases:

  1. Dealing with existing structures on disk.

  2. Advanced COM or Platform Invoke scenarios that involve structures with pointers in them.

  3. Performance-critical code.

In an unsafe context, a pointer type declaration takes one of the following forms:

type* identifier;

Ex:

int* ptr1; int* ptr1, ptr2;

Note: Pointer types do not inherit from Object and there is no conversions exist between pointer types and Object.

Unsafe code

Unsafe code in .Net Framework   c# vb.net

Unsafe code (unmanaged code ) allows you to manipulate memory directly. In the .NET environment, this is seen as potentially dangerous, and as such you have to mark your code as unsafe. Code written using an unsafe context cannot be verified to be safe, so it will be executed only when the code is fully trusted. That means, unsafe code cannot be executed in an untrusted environment, on the other hand, Managed Code has executed by the Common Language Runtime (CLR) environment. Click the following link to know more about .... Difference between managed and unmanaged code