29.8. Passing pointers to methods
Let'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: }
(1)Method takes in a parameter of type int*, a pointer
(2)Uses indirection to change the int value stored at the address in pX
(3)Invoke method by passing in the address of an int
Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.