Accessing a Member via Pointer (C# Programming Guide)
To access a member of a pointer type, use the member access expression that takes the form:
expression -> identifier
Parameters
- expression
A primary expression that evaluates to a pointer type, other thanvoid*
.
- ->
The member access operator.
- identifier
An accessible member of the type to which expression points.
Remarks
The member access operator -> is used to access fields or invoke methods of a struct through a pointer to the struct.
Example
In this example, a struct, CoOrds
that contains the two coordinates x
and y
is declared and instantiated. By using the member access operator -> and a pointer to the instance home
, x
and y
are assigned values.
Note
Notice that the expression p->x
is equivalent to the expression (*p).x
, and you can obtain the same result by using either one of the two expressions.
// compile with: /unsafe
struct CoOrds
{
public int x;
public int y;
}
class AccessMembers
{
static void Main()
{
CoOrds home;
unsafe
{
CoOrds* p = &home;
p->x = 25;
p->y = 12;
System.Console.WriteLine("The coordinates are: x={0}, y={1}", p->x, p->y );
}
}
}
Output
The coordinates are: x=25, y=12
See Also
Reference
Pointer Expressions (C# Programming Guide)
Pointer types (C# Programming Guide)
unsafe (C# Reference)
fixed Statement (C# Reference)
stackalloc (C# Reference)