Why it pays to read more than just the first compiler message

Error messages are frustrating. Especially when you can’t figure out why you are getting them.

Take this bit of code:

    private class MountainComparer : Comparer<Mountain>
    {
        public int Compare(Mountain x, Mountain y)
        {
            // compare the two mountains
            // for the purpose of this tests they are considered equal when their identifiers (names) match
            return x.Name.CompareTo(y.Name);
        }
    }

It produces a 'TestProject.ComparingCollections.SimpleDataAccessLayer_Tests.MountainComparer' does not implement inherited abstract member 'System.Collections.Generic.Comparer<ActualProject.ComparingCollections.Mountain>.Compare(ActualProject.ComparingCollections.Mountain, ActualProject.ComparingCollections.Mountain)' error for the MountainComparer class.

Wah?

What do you mean? The method is there. I am implementing it! I can see it right there!

Guess not. The compiler is rarely wrong.

So why is it complaining?

There is a clue in a warning message the compiler produces in addition to the error: 'TestProject.ComparingCollections.SimpleDataAccessLayer_Tests.MountainComparer.Compare(ActualProject.ComparingCollections.Mountain, ActualProject.ComparingCollections.Mountain)' hides inherited member 'System.Collections.Generic.Comparer<ActualProject.ComparingCollections.Mountain>.Compare(ActualProject.ComparingCollections.Mountain, ActualProject.ComparingCollections.Mountain)' on the Compare method itself.

And that warning message even tells you how to solve the error: To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.

When you do that, ie change

    public int Compare(Mountain x, Mountain y)

to

    public override int Compare(Mountain x, Mountain y)

then both the warning and the error disappear.

You’ll often find the solution to an error message right in the warnings or hints the compiler produces as a result of the same error in your code.

That is why it pays to read a bit more than just the first error message the compiler produces.

Enjoy!

What compiler error messages have had you stumped and turning to your colleagues or Google?
I’d love hearing from you by email or in the comments.

Posted in Software Development
Tags: , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Show Buttons
Hide Buttons