29.9 Using the -> member access operatorExamine the program below. 1: using System; 2: 3: public class TestClass{ 4: 5: public struct Temp{ 6: public int a; 7: public int b; 8: public void SaySomething(){ 9: Console.WriteLine("hi!"); 10: } 11: } 12: 13: public unsafe static void Main(){ 14: Temp temp = new Temp(); 15: Temp* pTemp = &temp; 16: 17: // invoke method of temp by indirection 18: (*pTemp).SaySomething(); 19: 20: // access field of temp by indirection 21: Console.WriteLine((*pTemp).a); 22: } 23: } Output: c:\expt> hi! 0 Line 18 invokes a method and line 21 retrieves the value of a field indirectly by applying the indirection operator on the pTemp pointer. C# has a simpler syntax to access a member. Instead of: (*pTemp).SaySomething(); it uses the -> operator like this: pTemp->SaySomething(); Similarly, the following two expressions are equivalent: (*pTemp).a pTemp->a The operand on the left of the -> operator must be a pointer type (except void* ), and the operand on the right must refer to an accessible member that matches the pointer's referent type. The -> operator does not add new functionality to unsafe coding, it simply serves to simplify the syntax of potentially intimidating codes. This operator can only be used in an unsafe context. |