Partager via


How to: Access a Member with a Pointer (C# Programming Guide)

To access a member of a struct that is declared in an unsafe context, you can use the member access operator as shown in the following example in which p is a pointer to a struct that contains a member x.

CoOrds* p = &home;
p -> x = 25; //member access operator ->

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 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 );
        }
    }
}

See Also

Reference

Pointer Expressions (C# Programming Guide)

Pointer types (C# Programming Guide)

unsafe (C# Reference)

fixed Statement (C# Reference)

stackalloc (C# Reference)

Concepts

C# Programming Guide

Other Resources

Types (C# Reference)