Is it possible for a caller of the following method to craft a string reference and pass it as token such that the method returns true? (Assuming the caller does not get the string reference from the static field using reflection.)
class GuessTheSecret
{
private static readonly string Secret = new string("Secret".ToCharArray());
public static bool IsCorrect(string token)
{
return object.ReferenceEquals(token, Secret);
}
}
No. You’d have to expose the static instance to the caller. Reference equality means that it is exactly the same object. Unless there is a way to access that particular object, you can’t have another that references the same memory. If you were to use the equality operator, that would be different as
stringoverloads that to do value equality rather than reference equality.Had you, on the other hand, set the static instance value to a constant, you could (by using the constant) have a reference that is equal to the static instance. That is because string literals are interned and shared through out the code, meaning that all string literals that are the same have the same reference.
For example,
would output
True