I am using jabber.net in C# and there is a quirk that has confused me so hopefully someone can explain how it is doing it. I am still quite new to C# from a C++ background so it may be a misunderstanding there
I am creating a readonly JID to hold a room that I need to enter:
private readonly JID messagingRoomJID;
public MyClass
{
// Reads from database but for purpose of this question
messagingRoomJID = new JID("user@myserver");
}
Later I want to join a room which is where I get the thing I am confused by
conferenceManager = new ConferenceManager();
conferenceManager.Stream = xmppClient;
// Before entering this room messagingRoomJID.Resource == null
theRoom = conferenceManager.GetRoom(messagingRoomJID);
// But now messagingRoomJID.Resource contains my username
But how is Resource being changed? The variable is readonly but also shouldn’t it be passed by const reference, so how is it being updated anyway?
It looks like I can do it by this but I am not sure it is sensible:
theRoom = conferenceManager.GetRoom(new JID(messagingRoomJID));
It’s not changing the value of your variable. The value of your variable is just a reference. That reference is staying the same as it was before.
What’s changing is the data within the object that the reference refers to. The
readonlymodifier only applies to your variable – it doesn’t say anything about the mutability of the object itself.It’s very important to distinguish between references and objects – see my article on the topic for more information.