Abstraction in C#: an overview
In code, abstraction means working with an object through the few things that matter to you, and ignoring the rest. Base classes already do this; abstract classes and interfaces take it further.
Apprentice · C# · OOP · Updated
After this lesson you can
- Explain abstraction as using an object through only the members that matter, and ignoring how they work
Key takeaways
- Abstraction means using an object for what it does, not how it does it, as you call
Sort()without reading its code. - The more general a class, the more abstract it is:
Characteris more abstract thanArcher. - C# has two tools for abstraction: an abstract class, a general idea you can't create, and an interface, a list of what something must be able to do to be used.
An abstract painting of a cat keeps a few lines and still says cat. Code does the same thing. Abstraction means working with something through the few details that matter to you right now, and ignoring all the rest.
You've used abstraction all along
Every time you call a method without reading its code, you're using abstraction:
List<string> names = new List<string> { "Grace", "Ada", "Linus" };
names.Sort();
Console.WriteLine(string.Join(", ", names));
Ada, Grace, Linus
You know what Sort() does: it puts the list in order. You don't know, or need to know, how it does it. The List<string> class hides hundreds of lines behind one word. That's abstraction: a simple outside over a complicated inside.
Base classes are abstractions too
In Polymorphism, a List<Character> held archers and wizards, and one loop called SpecialAbility() on each. The loop thought only in characters: a name and a special ability. Whether each one was an archer or a wizard, and how it worked out its ability, didn't matter to the loop.
The more general a class is, the more abstract it is. Character is more abstract than Archer, just as animal is more abstract than dog.
Where this chapter goes
C# gives you two tools to build abstractions on purpose:
| Tool | What it says |
|---|---|
| An abstract class | "This is a general idea. You can't make one; make a specific kind." |
| An interface | "Anything that can do these things can be used here." |
The next lessons build both, starting from the inheritance you already know.
Check yourself
1 question to try on the lesson page.
So what
Abstraction lets you think about what an object does, not how. That's how big programs stay understandable: each piece only needs to know the outside of the pieces it uses.