| Start |
|---|
| Introduction to unsafe code C# allows using pointer variables in a function of code block when it is marked by the A pointer is a variable whose value is the address of another variable i.e., the direct address of the memory location. similar to any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer declaration is: Following are valid pointer declarations: The following example illustrates use of pointers in C#, using the unsafe modifier: When the above code wass compiled and executed, it produces the following result: Instead of declaring an entire method as unsafe, you can also declare a part of the code as unsafe: |
| Accessing Array Elements Using a Pointer In C#, an array name and a pointer to a data type same as the array data, are not the same variable type. For example, Therefore, if you need to access an array data using a pointer variable, as we traditionally do in C, or C++, you need to fix the pointer using the fixed keyword. The following example demonstrates this: When the above code was compiled and executed, it produces the following result: |
| Compiling Unsafe Code For compiling unsafe code, you have to specify the For example, to compile a program named prog1.cs containing unsafe code, from command line, give the command: If you are using Visual Studio IDE then you need to enable use of unsafe code in the project properties. To do this: |
| Retrieving the Data Value Using a Pointer You can retrieve the data stored at the located referenced by the pointer variable, using the ToString() method. The following example demonstrates this: When the above code was compiled and executed, it produces the following result: |
| Passing Pointers as Parameters to Methods You can pass a pointer variable to a method as parameter. The following example illustrates this: When the above code is compiled and executed, it produces the following result: |
Read Article
https://develop.horje.com/learn/1434/reference