Madhawa Learns To Blog

.net, c#, sql, OOAD and more mad memory dumps...

Tuesday, March 07, 2006

Using pointers in C#?

Have you ever thought that we could use pointers in C#? Yes we could. I did it for fun 2 years ago when I was at iDial Networks among some strong C, C++ programmers. : )

Anyway today one of my friends asked me how to do that and I refreshed my knowledge on that so thought to share it here.

When you are using pointers in C# you have to tell the compiler about that clearly using unsafe keyword.

You can use unsafe modifier in the declaration of a type or a member. So the entire extent of the type or member will be considered as unsafe.

The scope of the unsafe context extends from the parameter list to the end of the method, so pointers can be used in the parameter list also.

unsafe static void FastCopy (byte* ps, byte* pd, int count)
{
// unsafe context: can use pointers here
}


You can use unsafe code blocks also like this.

unsafe
{
// unsafe context: can use pointers here
}


If you have unsafe code in your program, you have to specify the /unsafe compiler option. Otherwise you will get a compiler error. Unsafe code won’t verifiable by the CLR.

Unsafe code is in fact a "safe" feature from the perspective of both developers and users. Unsafe code must be clearly marked with the modifier unsafe, so developers can't possibly use unsafe features accidentally, and the execution engine works to ensure that unsafe code cannot be executed in an untrusted environment.

For more info in unsafe code refer to this.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vcwlkunsafecodetutorial.asp

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home