Chapter 5. Encapsulation: Keep your Privates… Private

Images

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.

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.

Images

Create a console app to calculate damage

Let’s build a console app for Owen that uses the SwordDamage class. It will print a prompt to the console asking the user to specify whether ...

Get Head First C#, 4th 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.