Working with Objects in C#: an overview
Object-oriented programming models software on the things around us, objects that each know some facts and do some jobs.
Novice · C# · OOP · Updated
After this lesson you can
- Explain how object-oriented programming models a program as objects
Key takeaways
- Object-oriented programming models a program as objects, each knowing some facts about itself and doing some jobs.
- An object keeps data that belongs together in one place, such as a team's name, wins and losses, and only the object changes it.
- You've used objects already: a
stringknows itsLengthand can do jobs likeToUpper().
So far, your programs have been lists of instructions, organized into methods. That works well for small jobs. But as programs grow, a long list of methods and loose variables gets hard to follow: which variables belong together? Which methods are allowed to change them?
Object-oriented programming (OOP) organizes a program differently. Instead of focusing only on methods and logic, you model your software on the world it serves, as objects with responsibilities.
The world is made of objects
In daily life, objects are the things you work with. Think of a kitchen: it's full of objects, and each one has a purpose. The refrigerator keeps food cold. The dishwasher cleans dishes. The oven heats things up. You don't need to know how a refrigerator keeps things cold to use one; you open the door, put food in, and trust it to do its job.
Software objects work the same way. A shopping site might have a Cart, a Product and an Order. A sports app might have a Team, a Game and a Player. Each object:
- knows some facts about itself: a team knows its name, its wins and its losses;
- does some jobs: a team can record a game's result, or work out its winning percentage.
Why build programs this way?
- Things that belong together stay together. A team's name, wins and losses travel as one object, not three loose variables.
- Each object guards its own data. Only the team changes its record, so a mistake can't creep in from anywhere in the program.
- Programs read like the problem.
team.RecordWin()says what's happening, in the words of the problem. - Objects are reusable. A
Teamwritten for one app works in the next.
You've used objects already. A string is an object: it knows its characters and its Length, and it can do jobs like ToUpper() and Split(). In this chapter you'll design and write objects of your own.
Check yourself
1 question to try on the lesson page.
So what
Object-oriented programming is how almost every large C# program is organized, from web apps to games: model the problem as objects, each knowing its own facts and doing its own jobs.