Safe code in C #

C # allows using pointer variables in a function of code block when it is marked by unsafe modifier. The concept of unsafe code or unmanaged code in C # is a code block that uses a pointer variable.

How to compile unsafe code in Visual Studio 2010

To compile and run programs in / unsafe mode, just right-click on Project , then select Properties -> Build -> Allow unsafe code and then press Ctrl + S to save the changes as shown in the picture:

Safe code in C # Picture 1

Pointer in C #

A pointer is a variable whose value is the address of another variable, for example, the direct address of the memory location. Similar to any other variable or constant in C #, you must declare a pointer before you can use it to store any variable address.

The general form of a cursor declaration in C # is:

 type * var - name ; 

Here are valid cursor declarations in C #:

 int * ip ; /* con trỏ tới một số nguyên */ double * dp ; /* con trỏ tới một số double */ float * fp ; /* con trỏ tới một số float */ char * ch /* con trỏ tới một ký tự */ 

The following example illustrates the use of pointers, using unsafe modifier in C #:

 using System ; namespace QTMCsharp { class TestCsharp { static unsafe void Main ( string [] args ) { Console . WriteLine ( "Con tro trong C#" ); Console . WriteLine ( "--------------------------------" ); int var = 20 ; int * p = & var ; Console . WriteLine ( "Du lieu: {0} " , var ); Console . WriteLine ( "Dia chi: {0}" , ( int ) p ); Console . ReadKey (); } } } 

If you do not use the Console.ReadKey () command; then the program will run and finish (so fast that you can not see the results). This command allows us to see the results more clearly.

Compiling and running the above C # program will produce the following results:

Safe code in C # Picture 2

Instead of declaring the entire method in unsafe format, you can also declare an unsafe code.

Revoke data values ​​by using pointers in C #

You can retrieve the data stored at the location referenced by the pointer variable, using the ToString () method in C #. Here is an example:

 using System ; namespace QTMCsharp { class TestCsharp { static void Main ( string [] args ) { Console . WriteLine ( "Con tro trong C#" ); Console . WriteLine ( "Unsafe code trong C#" ); Console . WriteLine ( "--------------------------------" ); unsafe { int var = 20 ; int * p = & var ; Console . WriteLine ( "Du lieu: {0} " , var ); Console . WriteLine ( "Du lieu: {0} " , p -> ToString ()); Console . WriteLine ( "Dia chi: {0} " , ( int ) p ); } Console . ReadKey (); } } } 

Compiling and running the above C # program will produce the following results:

Safe code in C # Picture 3

Pass the Cursor as Parameters to the method in C #

You can pass a pointer variable to a method as parameters. Here is an example:

 using System ; namespace QTMCsharp { class TestCsharp { public unsafe void swap ( int * p , int * q ) { int temp = * p ; * p = * q ; * q = temp ; } public unsafe static void Main () { Console . WriteLine ( "Unsafe code trong C#" ); Console . WriteLine ( "Truyen con tro nhu la tham so" ); Console . WriteLine ( "-----------------------------------" ); TestCsharp p = new TestCsharp (); int var1 = 10 ; int var2 = 20 ; int * x = & var1 ; int * y = & var2 ; Console . WriteLine ( "Truoc khi trao doi: var1 = {0}, var2 = {1}" , var1 , var2 ); p . swap ( x , y ); Console . WriteLine ( "Sau khi trao doi: var1 = {0}, var2 = {1}" , var1 , var2 ); Console . ReadKey (); } } } 

Compiling and running the above C # program will produce the following results:

Safe code in C # Picture 4

Access array elements using a pointer in C #

In C #, an array name and a pointer to the same data type as array data, are not the same type of variable. For example, int * p and int [] p, are not of the same type. You can quantify pointer p because it is not fixed in memory, but an array address is fixed in memory, and you cannot quantify it.

Therefore, if you need to access an array data using a pointer variable, as we did in C or C ++ (you can check: Cursor in C ), you need to fix that pointer Use the keyword fixed in C #.

Here is an example to illustrate:

 using System ; namespace QTMCsharp { class TestCsharp { public unsafe static void Main () { Console . WriteLine ( "Unsafe code trong C#" ); Console . WriteLine ( "Truy cap cac phan tu mang boi su dung con tro" ); Console . WriteLine ( "-----------------------------------" ); int [] list = { 10 , 100 , 200 }; fixed ( int * ptr = list ) /* mang dia chi trong con tro */ for ( int i = 0 ; i < 3 ; i ++) { Console . WriteLine ( "Dia chi cua list[{0}]={1}" , i , ( int )( ptr + i )); Console . WriteLine ( "Gia tri cua list[{0}]={1}" , i , *( ptr + i )); } Console . ReadKey (); } } } 

Compiling and running the above C # program will produce the following results:

Safe code in C # Picture 5

Follow tutorialspoint

Previous article: Anonymous method in C #

Next article: Multithread (Multithread) in C #

4.5 ★ | 2 Vote

May be interested

  • How to boot into Safe Mode on MacHow to boot into Safe Mode on Mac
    if your mac is having difficulty starting or you are experiencing startup problems, you should start your mac in safe mode to try to identify and resolve the problem. we'll show you how to do it.
  • Start Safe Mode on Windows XPStart Safe Mode on Windows XP
    with safe mode, your computer does not have to boot to work with windows as usual, but only loads the most basic files, the most essential drivers (by default windows) like the screen driver, desk. keys, mouse, storage device. of course, you will not be able to use the cd-rom, the printer, or you may not be able to connect to the network ... after you boot into safe mode, you may be able to resolve the problem from here. below, we will show you how to start safe mode on your system
  • What is QR code?What is QR code?
    qr codes have become increasingly popular, becoming a tool for logging into websites, wifi networks, sharing information, electronic payment, data storage or electronic tickets ...
  • How to access Safe Mode Windows 10 on startupHow to access Safe Mode Windows 10 on startup
    there are many ways to enter safe mode on windows 10, in case you cannot access windows and access it. to enter safe mode windows 10 when starting the computer, please refer to the following article of network administrator.
  • What is Safe Zone on Instagram?What is Safe Zone on Instagram?
    if you've ever tried viewing an instagram reel or story but couldn't understand its full meaning because some related content was hidden behind text or buttons, you're not the only one.
  • Check MD5 code, check MD5 code of any file on the computer quickly and accuratelyCheck MD5 code, check MD5 code of any file on the computer quickly and accurately
    check md5 code, check md5 code of any file on the computer quickly and accurately. when downloading files from the internet to a computer, we often check the md5 code to check the integrity of the file, make sure that the file is safe, as original as the website.
  • The classic cheat codes, almost every 8x 9x player knows by heartThe classic cheat codes, almost every 8x 9x player knows by heart
    cheat code, also known as cheat code, is the code, the statement ... added by the manufacturer to change some game features and help players 'clearing' easier.
  • Enable Safe Mode in Windows 7Enable Safe Mode in Windows 7
    there are many problems with the operating system when misconfiguring the software or installing the wrong driver, then the job we need to do is to uninstall what has just been done. however, there are many cases of unacceptable errors in the normal desktop. then we can use safe mode to fix this.
  • Google Safe Folders, 'secret storage room' for Android users to hide private informationGoogle Safe Folders, 'secret storage room' for Android users to hide private information
    this secret storage area is located in the file app on android smartphones and is protected by a password set by the user.
  • Family safes are good to buy the most todayFamily safes are good to buy the most today
    safes are effective items to protect family property. however, choosing which type of quality and safety is not everyone knows. read through the following article for more information.