Custom object to be used as key in a dictionary



I have the following code that is used to retrieve Orders of a client:

 public class Account
    public Account(int clientId, int server)
        ClientId = clientId;
        Server = server;

    public int ClientId { get; }
    public int Server { get; }

    public override bool Equals(object obj)
        var item = obj as Account;

        if (item == null)
            return false;

        return ClientId == item.ClientId
               && Server == item.Server;

    public override int GetHashCode()
        return (ClientId.GetHashCode() << 24)
               ^ Server.GetHashCode();

public class OrdersService
    private readonly Dictionary<Account, Orders> listOfClientOrders;

    public OrdersService(Dictionary<Account, Orders> listOfClientOrders)
        this.listOfClientOrders = listOfClientOrders;

    public Orders GetClientOrders(int clientId, int server)
        Account key = new Account(clientId, server);
        listOfClientOrders.TryGetValue(key, out Orders clientOrders);
        return clientOrders;

Inside OrdersService I have the orders of each client saved in a dictionary and I save/retrieve them using a custom class as dictionary key. If you take a look at the Account class I override Equals() and GetHashCode().
I have read the following article: Object.GetHashCode which states

“Do not use the hash code as the key to retrieve an object from a keyed collection.”

My question is. Does this affect my code on the OrdersService dictionary?



No, you’re doing it right. What that quote is saying is that you shouldn’t do something like:

int key = new Account(clientId, server).GetHashCode();
listOfClientOrders.TryGetValue(key, out Orders clientOrders);


Thanks for your reply.
But from my understanding GetHashcode() might produce different value every time is called. Based on my scenario inside the overriden GetHashcode of Account class I call GetHashcode for ClientId and Server. This might produce different values every time they are called.


No, it won’t. It might produce different value on different versions of .Net or even if you restart your application. But within a single process, the value is guaranteed to stay the same.

This means you can’t save the hash code to disk or to send it over network, but using it in Dictionary the way you are doing is safe. In fact, that’s the primary reason why GetHashCode() exists in the first place.


Thanks a lot for the clear explanation.

.NET Foundation Website | Blog | Projects | Code of Conduct