What is the unsafe keyword?
What is the unsafe keyword?
Rating:
The unsafe keyword is used in case of pointers in C#. The unsafe keyword denotes an unsafe code or block, which is required for any operation involving pointers. The unsafe keyword is applied as a modifier in the declaration of callable members such as methods, properties, and constructors (but not static constructors), as given below:
static unsafe void UnsafeTestFunc(string str, int count) //unsafe method
{
//unsafe code: can use pointers here
}
unsafe
{
//unsafe block
}
The following code snippet displays the use of the unsafe keyword:
using System;
class UnsafeTestCode
{
unsafe public static void Main()
{
int count = 99098;
int* pointer; //create an int pointer.
pointer = &count; //put address of count into pointer.
Console.WriteLine( "Initial value of count is " + *pointer);
*pointer = 10; //assign 10 to count via pointer.
Console.WriteLine( "New value of count is " + *pointer);
Console.ReadLine();
}
}
Rating:
Other articles
- Skills required for Microsoft test 70-536.
- How to change the Configuration property of a C# .NET project?
- What are the types of Breakingpoints?
- What is the StreamReader class?
- How to open Windows application?
