I intend to us the ToString() method for creating a cache key. This cache will be used to cache method level invocations and the key will be constructed by using the parameters names and corresponding values. Since this caching is going to be built for a large library I do not have the ability to ensure that every method has only value type parameters or all classes implement serialization. I need to determine at run time that the call to ToString is returning an actual value versus the type name so that that method invocation can be disallowed from participation in the caching.
for Instance, consider the following method and its invocation
AccountDetails GetDetails(int groupId, Account account)
{
var ac1 = new Account( accountId = 123 };
var ac2 = new Account( accountId = 555 };
var return1 = GetDetails(15, ac1);
var return2 = GetDetails(15, ac2);
}
In this case i would construct cache key as “groupId=15+account=namespace.Account” causing an incorrect collision. How do i detect at runtime that my call to account.GetString() is going to return a type name?
You shouldn’t be using strings for general cache keys. It’s really not what
ToStringwas designed for. Instead, you should be usingEqualsandGetHashCodeto check for equality. Of course, likeToString, every object hasEqualsandGetHashCodemethods… but fortunately, there’s theIEquatable<T>interface which provides a much stronger signal that a type was really designed for equality.So for any given type
X, just check whether that type implementsIEquatable<X>. If it does, it should be reasonable to use as a cache key. If you’re writing a generic method, you can enforce this: