Search code examples
c#c++design-patternsidiomsnon-virtual-interface

Is the Non-Virtual Interface (NVI) idiom as useful in C# as in C++?


In C++, I often needed NVI to get consistency in my APIs. I don't see it used as much among others in C#, though. I wonder if that is because C#, as a language, offers features that makes NVI unnecessary? (I still use NVI in C#, though, where needed.)


Solution

  • I think the explanation is simply that in C#, "traditional" Java-style OOP is much more ingrained, and NVI runs counter to that. C# has a real interface type, whereas NVI relies on the "interface" actually being a base class. That's how it's done in C++ anyway, so it fits naturally there.

    In C#, it can still be done, and it is still a very useful idiom (far more so, I'd say, than "normal" interfaces), but it requires you to ignore a built-in language feature.

    Many C# programmers just wouldn't think of a NVI class as being "a proper interface". I think this mental resistance is the only reason why it's less common in C#.