Search code examples
.netpointersstructunsaferef

In .NET is there any difference between using pointers as function parameters or using the "ref" keyword?


I have written a struct and functions where I try to pass the struct by reference (i.e. struct value can be modified inside functions).

enum RoomType { Economy, Buisness, Executive, Deluxe };

struct HotelRoom
{
    public int Number;
    public bool Taken;
    public RoomType Category;

    public void Print()
    {
        String status = Taken ? "Occupied" : "available";
        Console.WriteLine("Room {0} is of {1} class and is currently {2}", 
            Number, Category, status);
    }
}

Now to pass this struct by reference I've found two ways.

//Using Pointer
private unsafe static void Reserve(HotelRoom* room)
{
    if (room->Taken)
        Console.WriteLine("Cannot reserve room {0}", room->Number);
    else
        room->Taken = true;
}      

//Using ref keyword.
private static void Reserve(ref HotelRoom room)
{
    if (room.Taken)
         Console.WriteLine("Cannot reserve room {0}", room.Number);
    else
         room.Taken = true;
}    

Is there any difference? In general when should I use a pointer and when should I go for the ref keyword?


Solution

  • Pointers are considered unsafe.

    If you code in an unsafe context, like passing a reference by pointer to the function, someone can change your pointer to pointer somewhere else, and you get garbage data.

    If you use the ref keyword, the context is "safe", and you can't change where room is pointing to, only it's data like number, taken and category.