A practical guide to the Open-Closed Principle (OCP), the 'O' in SOLID, applied to C# and .NET. Covers the core idea that modules should be open for extension but closed for modification, illustrated with a shape-drawing example that evolves from type-checking if/else chains to an IShape interface abstraction. Also explores the Point of Variation principle as a more actionable framing, discusses the tension between OCP and YAGNI/KISS, and extends the example to the Visitor pattern for handling double dispatch when both shapes and algorithms need to vary independently. Includes practical tips on detecting OCP violations via downcasting, is/as operators, and static analysis tools like NDepend.

10m read timeFrom blog.ndepend.com
Post cover image
Table of contents
SOLID Principles SummaryOpen-Closed Principle Explained with a C# ExampleAnticipating Variations: the Point of Variation PrincipleBe Open to More Than One Variation with the Visitor PatternFrequently Asked Questions about the Open-Closed PrincipleConclusion
28 Impressions