Search code examples
c#stringvisual-studiocomparison

Member 'object.Equals(object, object)' cannot be accessed with an instance reference


[Note: there's another question about the same error-message, but the root cause of the issue there is a bit different, and none of the answers there apply to the below code.]

I have this code:

string localComputerName = Environment.MachineName;
foreach (StatsServer server in servers)
{
  if (localComputerName.Equals(server, StringComparison.OrdinalIgnoreCase)) {
    ...
  }
}

which gives me this compile-error at the call to Equals:

Member 'object.Equals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead

I was expecting it to use string.Equals(string, StringComparison), which is an instance method (not a static method); why does the compiler think I want object.Equals(object, object) instead?


Solution

  • What's happening is that string is an object, but it's not the same type of object as StatsServer, so Visual Studio gets confused and thinks the localComputerName variable is the problem, instead of server.

    From what I can determine, it decides this from the parameters of the Equals method, instead of by the datatype of from the variable the Equals is being applied to. (IMO, that's backwards, but evidently Microsoft has their reasons, and probably has something to do with how Equals is overloaded/extended onto all objects, or something.)

    I this case, the error is a red herring. What needs to happen is that I should access the ServerName property/column of server, since it is a string and has the data I actually want for comparison:

    if (localComputerName.Equals(server.ServerName, StringComparison.OrdinalIgnoreCase))
    

    The moral of the story is to make sure your objects are of the same datatype and to look at the whole line of code before assuming the JIT compiler is 100% accurate.