tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Default interface members and missing “public” in implementation

21 Sep 2022 1 mins C#

Recently I spent surprising amount of time chasing behavior that didn’t match my expectations. As you can guess the problem was between keyboard and chair. Hopefully my mistake can help you save minutes (or hours) of debugging.

Let’s have this simple interface.

interface IGotcha
{
	void DoGotcha();
	void DoMoreGotcha() => DoGotcha();
}

And implementation.

class Gotcha : IGotcha
{
	public void DoGotcha()
	{
		Console.WriteLine("Gotcha");
	}

	void DoMoreGotcha()
	{
		Console.WriteLine("MoreGotcha");
	}
}

With these pieces in place, what does this code print?

static void Main()
{
	var g = new Gotcha();
	DoGotcha(g);
}

static void DoGotcha(IGotcha g)
{
	g.DoGotcha();
	g.DoMoreGotcha();
}

If you answered 2x Gotcha, you’re right. What you might expect to get is Gotcha and MoreGotcha. But why is that not the correct answer? Because the Gotcha.DoMoreGotcha is not public (I intentionally made it implicit private in my example, but i.e., (explicit) internal would do the same and would be probably harder to spot.), it’s not implementation of IGotcha.DoMoreGotcha. Makes absolute sense, right?

Hope this realization saves you minutes (or hours) next time you have weird confusing behavior like this.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.