C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » C# Syntax »

Use of unsafe keyword in C#


Posted Date: 06 Nov 2009    Resource Type: Code Snippets    Category: C# Syntax
Author: Abhisek PandaMember Level: Gold    
Rating: 1 out of 5Points: 10



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



Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Unsafe keyword in C#  .  Unsafe  .  Keyword  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Converting a stream reader to xml reader
Previous Resource: Email Validation
Return to Discussion Resource Index
Post New Resource
Category: C# Syntax


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use