Chapter 5. Encapsulation How objects keep their Secrets

Ever wished for a little more privacy?

Sometimes your objects feel the same way. Just like you don’t want anybody you don’t trust reading your journal or paging through your bank statements, good objects don’t let other objects go poking around their fields. In this chapter, you’re going to learn about the power of encapsulation, a way of programming that helps you make code that’s flexible, easy to use, and difficult to misuse. You’ll make your objects’ data private, and add properties to protect how that data is accessed—and you’ll keep your object’s important data from leaking out to other objects so they don’t accidentally misuse it.

Let’s help Owen roll for damage

Owen was so happy with his ability score calculator that he wanted to create more C# programs he can use for his games, and you’re going to help him. In the game he’s currently running, any time there’s a sword attack he rolls dice and uses a formula that calculates the damage. Owen wrote down how the sword damage formula works in his game master notebook.

Here’s a class called SwordDamage that does the calculation. Read through the code carefully—you’re about to create an app that uses it.

Create a console app to calculate damage

Let’s build ...

Get Head First C#, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.