.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Use of unsafe keyword in C#

Posted By:Abhisek Panda       Posted Date: November 10, 2009    Points: 25    Category: C#    URL: http://www.dotnetspark.com  
 

Unsafe Keyword


           In C# the value can be directly referenced to a variable, so there is no need of pointer. Use of pointer sometime crashes the application. But C# supports pointer, that means we can use pointer in C#.

           The use of pointer in C# is defined as a unsafe code. So if we want to use pointer in C# the pointer must be present in the body of unsafe declaration. But pointer does not come under garbage collection.


unsafe
{
int a, *b;
a = 25;
b = &a;
Console.WriteLine("b= {0}",b);//returns b= 25
}

See the below program for swapping of two numbers using pointer in C#.

class Swapping
{

//declaring pointers inside unsafe code
unsafe public static void UnsafeSwap(int* i, int* j)
{
int temp = *i;
*i = *j;
*j = temp;
}

static void Main(string args[])

{
// Values for swapping.

int i = 10, j = 20;
// Swap values using pointer

Console.WriteLine("Values before swap: i = {0}, j = {1}", i, j);

unsafe //passing the values to unsafe code
{
UnsafeSwap(&i, &j);
}

Console.WriteLine("Values after swap: i = {0}, j = {1}", i, j);

}
}
Output:-
Values before swap: i = 10, j = 20
Values after swap: i = 20, j = 10
 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend