Unsafe code in C# is the part of the program that runs outside the control of the Common Language Runtime (CLR) of the .NET frameworks. The CLR is responsible for all of the background tasks that the programmer doesn’t have to worry about like memory allocation and release, managing stack etc. Using the keyword “unsafe” means telling the compiler that the management of this code will be done by the programmer. Making a code content unsafe introduces stability and security risks as there are no bound checks in cases of arrays, memory related errors can occur which might remain unchecked etc.
A programmer can make the following sub-programs as unsafe:
- Code blocks
Need to use the unsafe code?
- When the program needs to implement pointers.
- If native methods are used.
Example: Here, we are declaring a block of code inside main as unsafe so that we can use pointers.
Note: This code will not compile directly, it gives the following error.
Therefore, if you are using Visual Studio, then you need to follow the given steps:
1) Go to the project properties
2) Select the build option and check the “Allow unsafe code” option.
- Managed code and Unmanaged code in .NET
- Difference between Managed and Unmanaged code in .NET
- C# | How to get hash code for the specified key of a Hashtable
- Getting the hash code of the ValueTuple in C#
- Getting the Hash Code of the Specified Range in C#
- Getting the Hash Code of the Given Index in C#
- C#- Nested loops
- C# - Infinite Loop
- C# - if else Statement
- C# - if Statement
- C# - continue Statement
- C# - Break statement
- C# - Indexers Using String as an Index
- Different Types of HTML Helpers in ASP.NET MVC
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.