While I was working with the following piece of code, which works fine, I noticed that the _connections variable was declared private readonly, but then its value was actually changed, not only in the declaration or in the constructor as I would expect. I couldn't figure out why. Can someone help me understand why this works?

public class WebSocketConnectionManager { private readonly ConcurrentDictionary<string, WebSocket> _connections = new(); public async Task AddConnectionAsync(Int64 userId, string connectionId, WebSocket webSocket) { _connections.TryAdd(connectionId, webSocket); Console.WriteLine($"Connection added: {connectionId}. Total connections: {_connections.Count}"); var notification = new { type = "user_joined", connectionId = connectionId, totalConnections = _connections.Count }; } public async Task RemoveConnectionAsync(string connectionId) { if (_connections.TryRemove(connectionId, out var webSocket)) { if (webSocket.State == WebSocketState.Open) { await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Connection closed", CancellationToken.None); } Console.WriteLine($"Connection removed: {connectionId}. Total connections: {_connections.Count}"); var notification = new { type = "user_left", connectionId = connectionId, totalConnections = _connections.Count }; } } }

user3262353's user avatar

2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.