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?