Regarding my article "How to use Pointers in C#" http://www.shahidriaz.com/post/2008/09/22/Unsafe-code-in-Net.aspx alot of people started to ask that why I posted this article and why shoud we use unsafe in C# even some of said to me that I should close my web
First of all I would like to say that in that article I never said that start using pointers and unsafe code in C#. The idea behind was just for the beginners because most of the people think that we can not use pointers in C#.
Now here I am mentioning the scenarios where using pointers is more suitable as compared to other techniques.
What should I do if I am using some external DLL which is not being developed in .Net. Well some will say that creating a RCW (Run time callable wraper) is the solution of using non. Net DLL in .Net. I agree with them, but what if that RCW has a function in it which is taking some pointer as parameter?? I am sure that all of you will find the answer of their question that why and when to use pointers in C#.
I think that if some one is using the non .Net dll in their application then the above scenario will be halpfull for him.
Now lets talk about some other cases where we have to use pointers and unsafe keyword in C#.
Some old third parties control still use pointers. So again we have to use pointers in C# to address those third parties.(e.g. Most of the SDK of Biomatric devices are in VC which used pointers extensivly, Windows API etc)
Well these all were my own thoughts because I though alot today becasue I was also speechless when people started to ask these question, but I was also sure that there will be some reason of unsafe in C# and that is why microsoft introduced it.
Now I have also done some googling and I am copying some of the lines that why to use pointers in C#.
- Performance and flexibility, by using pointer you can access data and manipulate it in the most efficient way possible.
- Memory Addresses, there is no way to know the memory address of some data without using pointers.
Disadvantages of Unsafe Code in C#:
- Complex syntax, to use pointers you need to go throw more complex syntax than we used to experience in C#.
- Harder to use, you need be more careful and logical while using pointers, miss using pointers might lead to the following:
- Overwrite other variables.
- Stack overflow.
- Access areas of memory that doesn?t contain any data as they do.
- Overwrite some information of the code for the .net runtime, which will surely lead your application to crash.
- Your code will be harder to debug. A simple mistake in using pointers might lead your application to crash randomly and unpredictably.
- Type-safety, using pointers will cause the code to fail in the .net type-safety checks, and of course if your security police don?t allow non type-safety code, then the .net framework will refuse to execute your application.
Sorry for my poor english..