29.9. Using the -> member access operator

Examine 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(); ...

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.