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

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

Last updated on 02nd Feb 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) | 18526 Ratings 1650
    • Introduction to Unsafe Code in C#
    • Involving Unsafe Code in Visual Studio IDE
    • Perilous Context_declaration
    • Pointers
    • Assembling Unsafe Code
    • Instances of Unsafe Code
    • Conclusion

    Subscribe For Free Demo

    [custom_views_post_title]

      Introduction to Unsafe Code in C# :-

    • Dangerous code in C# is the piece of the program that runs outside the control of the Common Language Runtime (CLR) of the .NET structures.
    • The CLR is answerable for all of the foundation errands that the software engineer doesn’t need to stress over like memory designation and delivery, overseeing stack and so forth Utilizing the catchphrase “perilous” signifies let the compiler know that the administration of this code will be finished by the software engineer.
    • Making a code content perilous presents strength and security hazards as there are no bound checks in instances of clusters, memory related mistakes can happen which may stay unchecked and so forth
    • Dangerous code overall is a catchphrase that signifies a code area that isn’t dealt with by the Common Language Runtime(CLR). Pointers are not upheld naturally in C# yet hazardous catchphrase permits the utilization of the pointer factors.
    •   Unsafe Code in C#
       Unsafe Code in C#
    • Notwithstanding, additional consideration is expected while taking care of dangerous code to forestall mistakes or security chances as pointers are complicated and may prompt memory related blunders, for example, stack flood, overwritten framework memory and so forth

    • Involving Unsafe Code in Visual Studio IDE :-

      Hazardous code can be utilized in Visual Studio IDE by following the given advances:

      1. Double snap properties in the Solution Explorer to open task properties.

      2. Click the Build tab and select the choice “Permit Unsafe Code”.

      This empowers the utilization of hazardous code in Visual Studio IDE.

      A developer can make the accompanying sub-programs as hazardous:

      1. Code squares

      2. Methods

      3. Types

      4. Class

      5. Struct


      Perilous Context_declaration :-

      Model: Here, we are pronouncing a square of code inside principle as risky with the goal that we can utilize pointers.


      • // C# program to demonstrate the unsafe code
      • using System;
      • namespace GFG {
      • class Program {
      • // Main Method
      • static void Main(string[] args)
      • {
      • // Declaring a code block as
      • // unsafe to make use of pointers
      • unsafe
      • {
      • int x = 10;
      • int* ptr;
      • ptr = &x;
      • // displaying value of x using pointer
      • Console.WriteLine(“Inside the unsafe code block”);
      • Console.WriteLine(“The value of x is ” + *ptr);
      • } // end unsafe block
      • Console.WriteLine(“\nOutside the unsafe code block”);
      • } // end main
      • }
      • }

      Thusly, on the off chance that you are utilizing Visual Studio, you really want to follow the given advances:

    • Go to the task properties
    • Course Curriculum

      Learn Advanced C# Certification Training Course to Build Your Skills

      Weekday / Weekend BatchesSee Batch Details
    • Select the form choice and check the “Permit risky code” choice.

    • Output:

    • C# permits involving pointer factors in an element of code block when it is set apart by the hazardous modifier. The perilous code or the unmanaged code is a code block that utilizes a pointer variable.
    • Note − To execute the projects referenced in this section at coding ground, if it’s not too much trouble, set assemblage choice in Project >> Compile Options >> Compilation Command to mcs *.cs – out:main.exe – dangerous”

    • Pointers :-

      A pointer is a variable whose worth is the location of another variable i.e., the immediate location of the memory area. like any factor or steady, you should announce a pointer before you can utilize it to store any factor address.

      Following are legitimate pointer statements −

    • int *ip;/* pointer to a whole number */
    • twofold *dp;/* pointer to a twofold */
    • float *fp;/* pointer to a float */
    • singe *ch/* pointer to a person */
    • The accompanying model delineates utilization of pointers in C#, utilizing the hazardous 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();
      • }
      • }
      • }
      • Output
      • Information is: 20
      • Address is: 99215364

      Rather than pronouncing a whole technique as perilous, you can likewise proclaim a piece of the code as hazardous. The model in the accompanying segment shows this. Recovering the Data Value Using a Pointer You can recover the information put away at the found referred to by the pointer variable, utilizing the ToString() strategy. The accompanying model exhibits this −


      • using System;
      • namespace UnsafeCodeApplication {
      • class Program {
      • public static void Main() {
      • unsafe {
      • int var = 20;
      • int* p = &var;
      • Console.WriteLine(“Data is: {0} ” , var);
      • Console.WriteLine(“Data is: {0} ” , p->ToString());
      • Console.WriteLine(“Address is: {0} ” , (int)p);
      • }
      • Console.ReadKey();
      • }
      • }
      • }
      • output
      • Information is: 20
      • Information is: 20
      • Address is: 77128984

      Passing Pointers as Parameters to Methods :

      You can pass a pointer variable to a technique as boundary. The accompanying model outlines this −

      • using System;
      • namespace UnsafeCodeApplication {
      • class TestPointer {
      • public unsafe void swap(int* p, int *q) {
      • int temp = *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 = &var2;
      • Console.WriteLine(“Before Swap: var1:{0}, var2: {1}”, var1, var2);
      • p.swap(x, y);
      • Console.WriteLine(“After Swap: var1:{0}, var2: {1}”, var1, var2);
      • Console.ReadKey();
      • }
      • }
      • }
      • Output :
      • Prior to Swap: var1: 10, var2: 20
      • After Swap: var1: 20, var2: 10

      Getting to Array Elements Using a Pointer :

      In C#, an exhibit name and a pointer to an information type same as the cluster information, are not a similar variable sort. For instance, int *p and int[] p, are not same sort. You can increase the pointer variable p since it isn’t fixed in memory yet an exhibit address is fixed in memory, and you can’t augment that. In this manner, in the event that you really want to get to a cluster information utilizing a pointer variable, as we customarily do in C, or C++ ( kindly check: C Pointers), you really want to fix the pointer utilizing the proper catchphrase. The accompanying model shows this −


      • using System;
      • namespace UnsafeCodeApplication {
      • class TestPointer {
      • public unsafe static void Main() {
      • int[] list = {10, 100, 200};
      • fixed(int *ptr = list)
      • /* let us have array address in pointer */
      • for ( int i = 0; i < 3; i++) {
      • Console.WriteLine(“Address of list[{0}]={1}”,i,(int)(ptr + i));
      • Console.WriteLine(“Value of list[{0}]={1}”, i, *(ptr + i));
      • }
      • Console.ReadKey();
      • }
      • }
      • }
      • Output−
      • Address of list[0] = 31627168
      • Value of list[0] = 10
      • Address of list[1] = 31627172
      • Value of list[1] = 100
      • Address of list[2] = 31627176
      • Value of list[2] = 200

      Course Curriculum

      Get JOB Oriented C# Training for Beginners By MNC Experts

      • Instructor-led Sessions
      • Real-life Case Studies
      • Assignments
      Explore Curriculum

      Assembling Unsafe Code :-

      For assembling perilous code, you need to determine the/dangerous order line switch with order line compiler.

      For instance, to assemble a program named prog1.cs containing perilous code, from order line, provide the order − csc/risky prog1.cs

       Assembling Unsafe Code
      Assembling Unsafe Code

      On the off chance that you are utilizing Visual Studio IDE, you want to empower utilization of dangerous code in the task properties.

      To do this −

    • Open task properties by double tapping the properties hub in the Solution Explorer.
    • Click on the Build tab.
    • Select the choice “Permit risky code”.

    • Instances of Unsafe Code :-

      A portion of the instances of risky code executing pointers are given as follows:

      Model 1 :

      A program that exhibits the pointer presentation and information reference utilizing pointers is given as follows: Source Code: Program to exhibit pointer assertion and information reference involving pointers in C#


      • using System;
      • namespace PointerDemo
      • {
      • class Example
      • {
      • static unsafe void Main(string[] args)
      • {
      • char val = ‘A’;
      • char* ptr = &val;
      • Console.WriteLine(“The character value is: {0} “, val);
      • Console.WriteLine(“Address of the value is: {0}”, (int)ptr);
      • }
      • }
      • }
      • The output
      • The character value is: A
      • Address of the value is: 220412608

      Presently let us comprehend the above program.

      The person variable val contains A. Pointer ptr focuses to val for example it contains the location of val. Then, at that point, the upsides of val and ptr are shown. The code scrap for this is given as follows:

    • char val = ‘A’;
    • char* ptr = &val;
    • Console.WriteLine(“The character value is: {0} “, val);
    • Console.WriteLine(“Address of the value is: {0}”, (int)ptr);

    • C and C Plus Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

      Conclusion :-

      Unsafe code in general is a keyword that denotes a code section that is not handled by the Common Language Runtime(CLR). Pointers are not supported by default in C# but unsafe keyword allows the use of the pointer variables.


    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free