comment 0

C# Encapsulation: Keeping It All In the Family

Quick, what’s the difference between public, private, protected, and internal? If you are just learning encapsulation for the first time, this can be tough to remember. I find it easiest to remember which is which if I think of properties like the real world things. To keep things simple, let’s say that you have a super chill hat that you need to decide what to do with.

Public is the easiest one to remember from the coding side of things. It’s basically communal property. Anyone can come wear your hat for a day and look oh so fly. The downside is that you can’t control what they do with it, and you may not be happy with the results. Once something is public, you are just hoping that it won’t get abused somewhere down the line. Commonly this is what you want, but often properties are made public that don’t need to be. You can mitigate this a bit with properties that have a public get method but the set method either contains some validation or has a stricter encapsulation. That way you may not get to control who wears your hat, but you don’t have to worry about someone randomly dying it blue.

Private is mine and no one else’s. Only you can wear your hat, and you only do it when you are home alone- no one even has to know you have it. From a coding perspective, this means that the property or method is only accessible by methods within that class- no outsiders allowed. This even applies to another copy of the object or classes that inherit from the base class. You’ve hidden your hat from not only the world at large but your twin brother or sister and your kids to boot.

Protected is kind of like private in that outsiders can’t access your hat. However, by some miracle, your kids think your hat is the best accessory they’ve ever seen, so you let them wear it as well. I won’t go too deeply into inheritance here, but if you want other classes to inherit from a given class, you often want to choose protected over private.

Internal keeps things in the family but isn’t restricted by inheritance. Your second cousin twice removed, Bob, can borrow your hat if he promises to bring it back promptly after his date, but you would never let a complete stranger wear your hat. In some ways, it works like public, but only within the same assembly. When working in Visual Studio you’ll only be able to call it within the same project. Once compiled each project will become its own assembly. Useful for methods and properties that are only used within an application layer, or if you need to be sure another dev won’t be able to get to the item by adding your DLL to their project.

Leave a Reply

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