C unsafe code LEARNOVITA

Unsafe Code in C-Sharp Tutorial | Everything You Need to Know

Last updated on 18th Aug 2022, Blog, Tutorials

About author

Madhuri (C# Automation Tester )

Madhuri is a C# Automation Tester and She has tons of experience in the areas of HTTP, SOAP/REST, VisualStudio, TFS, etc., CI/CD, functional, regression, and .NET technology stack. She spends most of her time researching technology, and startups.

(5.0) | 19571 Ratings 2087

Introduction to Unsafe Code in C# :

Dangerous code in C# is that the piece of the program that runs outside the management of the Common Language Runtime (CLR) of the .NET structures. The CLR is in control of all of the inspiration errands that the engineer doesn’t ought to stress over like memory designation and delivery, overseeing stack and then forth Utilizing the motto “perilous” signifies let the compiler grasp that the administration of this code are going to be finished by the engineer. Making a code content precarious presents strength and security hazards as there are not any sure checks in instances of clusters, memory connected mistakes will happen which can keep uncurbed and then forth Dangerous code overall may be a motto that signifies a code space that isn’t handled by the Common Language Runtime(CLR). Pointers aren’t upheld naturally in C# Nevertheless, the dangerous motto permits the use of the pointer factors. Notwithstanding, further thought is predicted whereas taking care of dangerous code to forestall mistakes or security probabilities as pointers square measure sophisticated and should prompt memory connected blunders, as an example, stack flood, overwritten framework memory and then forth.

Hazardous code are often utilized in Visual Studio IDE by following the given advances:

    1. 1. Double snap properties within the answer mortal to open task properties.
    2. 2. Click the Build tab and choose the selection “Permit Unsafe Code”.

This empowers the use of dangerous code in Visual Studio IDE.

A developer will build the attendant sub-programs as hazardous:

    1. 1. Code squares
    2. 2. Methods
    3. 3. Types
    4. 4. Class
    5. 5. Struct

Perilous Context_declaration :

Model: Here, we tend to area units announcing a sq. of code within principle as risky with the goal that we are able to utilize pointers.

  • using System;
  • namespace GFG methodology
  • static void Main(string[] args)
  • to create use of pointers
  • unsafe
  • worth of x mistreatment pointer
  • Console.WriteLine(“Inside the unsafe code block”);
  • Console.WriteLine(“The price of x is ” + *ptr);
  • } // finish unsafe block
  • Console.WriteLine(“\nOutside the unsafe code block”);
  • } // finish main
  • }
  • }

Thusly, on the off likelihood that you just area unit utilizing Visual Studio, you actually wish to follow the given advances:

Go to the task properties Select the shape selection and check the “Permit risky code” selection.


C# permits involving pointer factors in a part of code block once it’s set apart by the venturesome modifier. The touch-and-go code or the unmanaged code could be a code block that utilizes a pointer variable. Note − To execute the comes documented during this section at secret writing ground, if it’s not an excessive amount of bother, set assemblage selection in Project >> Compile choices >> Compilation Command to mcs *.cs – out:main.exe – dangerous”.

Pointers :

A pointer could be a variable whose price is the location of another variable i.e., the immediate location of the memory space. like all issues or steady, you ought to announce a pointer before you’ll be able to utilize it to store any issue address.

Following area unit legitimate pointer statements −

  • int *ip;/* pointer to an entire range */
  • twofold *dp;/* pointer to a twofold */
  • float *fp;/* pointer to a float */
  • singe *ch/* pointer to someone */

The related to model delineates utilization of pointers in C#, utilizing the venturesome modifier −

  • using System;
  • namespace UnsafeCodeApplication power unit = 20;
  • int* p = &var;
  • Console.WriteLine(“Data is: “, var);
  • Console.WriteLine(“Address is: ”, (int)p);
  • Console.ReadKey();
  • }
  • }
  • }


  • Data is: twenty
  • Address is: 99215364

Rather than announcing an entire technique as dangerous , you’ll likewise proclaim a bit of the code as unsafe. The model within the concomitant section shows this. convalescent the info worth employing a Pointer you’ll recover the knowledge place away at the found noted by the pointer variable, utilizing the ToString() strategy. The concomitant model exhibits this −

  • using System;
  • namespace UnsafeCodeApplication volt-ampere = 20;
  • int* p = &var;
  • Console.WriteLine(“Data is: ” , var);
  • Console.WriteLine(“Data is: ” , p->ToString());
  • Console.WriteLine(“Address is: ” , (int)p);
  • }
  • Console.ReadKey();
  • }
  • }
  • }


  • Data is : twenty
  • data is: twenty
  • Address is: 77128984

Passing Pointers as Parameters to strategies :

You can pass a pointer variable to a method as a boundary. The concomitant model outlines this −

  • using System;
  • namespace UnsafeCodeApplication temporary worker = *p;
  • *p = *q;
  • *q = temp;
  • }
  • public unsafe static void Main() {
  • TestPointer p = new TestPointer();
  • int var1 = 10;
  • int var2 = 20;
  • int* x = &var1;
  • int* y = &var 2;
  • Console.WriteLine(“Before Swap: var1:, var2: ”, var1, var2);
  • p.swap(x, y);
  • Console.WriteLine(“After Swap: var1:, var2: ”, var1, var2);
  • Console.ReadKey();
  • }
  • }
  • }

Output :

  • Prior to Swap: var1: ten, var2: 20
  • After Swap: var1: twenty, var2: 10

Getting to Array parts employing a Pointer :

In C#, associate degree exhibit name associate degreed a pointer to an data kind same because the cluster data, don’t seem to be an identical variable type. for example, int *p and int[] p, don’t seem to be the same type. you’ll increase the pointer variable p since it isn’t fastened in memory nonetheless associate degree exhibit address is fastened in memory, and you can’t augment that. During this manner, within the event that you just really need to induce a cluster data utilizing a pointer variable, as we tend to usually waste C, or C++ ( kindly check: C Pointers), you actually need to mend the pointer utilizing the right slogan. The related to model shows this −

Assembling Unsafe Code :

For collection unsafe code, you would like to see the/dangerous order line switch with order line compiler. For instance, to assemble a program named prog1.cs containing unsafe code, from order line, offer the order − csc/risky prog1.csOn the off chance that you just square measure utilizing Visual Studio IDE, you would like to empower utilization of dangerous code within the task properties. To do to try and doOpen task properties by double sound the properties hub within the answer adventurer. Click on the Build tab. Select the selection “Permit risky code”.

Assembling Unsafe Code

Instances of Unsafe Code :

A portion of the instances of risky code capital punishment pointers square measure given as follows:

Model 1 :

A program that exhibits the pointer presentation and knowledge reference utilizing pointers is given as follows: supply Code: Program to exhibit pointer assertion and knowledge reference involving pointers in C#MPresently allow us to comprehend the higher than program. The person variable val contains A. Pointer ptr focuses on val as an example it contains the placement of val. Then, at that time, the upsides of val and ptr square measure are shown. The code scrap for this can be given as follows:

  • char val = ‘A’;
  • char* ptr = &val;
  • Console.WriteLine(“The character price is: “, val);
  • Console.WriteLine(“Address of the worth is: ”, (int)ptr);
  • Conclusion :

    Unsafe code generally may be a keyword that denotes a code section that’s not handled by the Common Language Runtime(CLR). Pointers don’t seem to be supported by default in C# However, unsafe keywords permit the utilization of the pointer variables.

    Are you looking training with Right Jobs?

    Contact Us

    Popular Courses