29.8 Passing pointers to methodsLet's put together what we have learnt so far, and take a look at a general example of how pointers are passed between methods. Examine this program: 1: using System; 2: 3: class TestClass{ 4: 5: static unsafe void PerformOp ( int* pX ){ <-- 1 6: * pX = 99; <-- 2 7: } 8: 9: public static unsafe void Main(){ 10: int a = 1; 11: Console.WriteLine("a was :" + a); 12: PerformOp (&a); <-- 3 13: Console.WriteLine("a is :" + a); 14: } 15: }
Output: c:\expt>test a was :1 a is :99 In the example above, the PerformOp method (lines 5 “ 7) is marked with the unsafe modifier. It takes in a pointer to an int , dereferences the pointer to obtain the address where the int is stored, and stores the value 99 there. Main has to be marked as unsafe too because it uses the indirection operator to get the address of local int variable a . The output shows that local variable a has been altered by PerformOp . |