In
this article, we will understand the concept of pointers in C# and how we can
use it in our C# code. While learning, I heard that C# does not support pointer
which is not exactly true. It does support pointers but we do not have full
control over it as in C++. Basically, to maintain type safety and security, C#
does not support pointers but by explicit changes we can work with C# pointers.
Use of 'unsafe' keyword
By using ‘unsafe’ keyword, you can perform an operation that deals with pointers. Code or method used ‘unsafe’ modifier does not mean it is not safe but it is not verifiable by CLR. Unsafe code blocks are not dangerous but its safety does not verified by CLR, means if you are using pointers it is your responsibility to handle security risks and pointer errors.
Defining with ‘unsafe’ keyword
Use of 'unsafe' keyword
- Unsafe keyword can be used with- methods, types or code blocks.
- Use of ‘unsafe’ keyword introduced security risks, as these are not handled by CLR and it is developer’s responsibility to manage all.
- Use of ‘unsafe’ keyword can increase the application’s performance as it directly working wit memory addresses.
Defining with ‘unsafe’ keyword
Example: 1
public unsafe void TestUnsafe()
{
//TODO:
}
Example: 2
public void TestUnsafe()
{
unsafe
{
//TODO:
}
}
Compiling above code you may get below error:
Unsafe code may only appear if compiling with /unsafe
To resolve it, right click on project > properties >
Select ‘Build’ tab, check the option for ‘Allow unsafe code’.
Save it and now compile.
No comments:
Post a Comment