![]() |
|
Pointers in C#, Free online C# Programming Tutorial... |
| Lessons | C# Pointers |
|
int i = 5; int *p; p = &i; // take address of i *p = 10; // changes the value of i to 10 One major difference between C++ and C# is that the ‘*’ applies to the type. That is, as opposed to C++, in C#, the following statement would declare two pointers p1 and p2: int * p1, p2; Just like C++, the dereference operator ‘->’ is used to access elements of a struct type. Keyword 'unsafe' The keyword unsafe is used while dealing with pointers. The code dealing with pointers has to be written within the unsafe block{ }. The name reflects the risks that you might face while using it. static void Main() { //can't use pointers here unsafe { //you can declare and use pointer here } //can't use pointers here } We can also declare a whole class as unsafe as shown below: unsafe class Class1 { //you can use pointers here! } If you wish you can declare a method as unsfe as well as shown in the following piece of code: unsafe void MyMethod() { //you can use pointers here }
Next >>> Lesson No. 11: C# Pointers 2
|