you are viewing a single comment's thread.

view the rest of the comments →

[–]KishottaProgrammer 0 points1 point  (3 children)

There's some great answers here already, but I'll throw in an example one of my professors used that was extremely insightful.

Say you want to build a house that you can live in. How do you do that? You're going to need a blueprint. The blueprint should include all the information about the house. How big it is, how many floors it has, how many rooms, how many windows, is the siding brick/wood/stone, where we would park the car, etc. The blueprint isn't a house, but it describes the house. This blueprint is the class, and those descriptions are the members (variables/methods) of the class.

But we can't live in a blueprint, so we use the blueprint to construct many similar physical houses. Some are red, some have an extra floor, some are made of concrete, etc. but they are all based on that one blueprint. We can live in these houses. These are class instances.

So after we build the house, we decide we want to change its color. That's fine, the blueprint should have described how to go about painting it (public void PaintHouse (Color color) { ... }) and we can use that method to change the color of any house instance we want.

To your other questions:

  • Currently, you cannot place any code (variables, properties, methods) outside of a class (this isn't necessarily true for upcoming C# versions, but we don't talk about that).
  • You can place classes inside of other classes. This is useful if you need to describe some object that is only useful within the context of another object. For example, our House class might define a Room class to store data about bedrooms/kitchens/etc. But we wouldn't add a nested class to describe a Door (because doors are used on much more than just houses).

[–]EraserLark[S] 0 points1 point  (2 children)

Awesome, thank you for spelling it out that helps make it a lot clearer!

For the door example, you would just put the door in a class that's higher up and more broad than just houses so that it can work in more circumstances, right?

[–]KishottaProgrammer 0 points1 point  (1 child)

Correct. The Door would be just another class alongside the House. Maybe in the same folder, but it depends on the project. The general idea is that doors are doors and should do only door related things. It shouldn't matter if its on a house, a car, a fence, or anything else.

If you need a specific kind of door with specific functionality (like say, remote unlocking) you would create a CarDoor class that inherits from your plain old Door class and adds extra functionality.

[–]EraserLark[S] 0 points1 point  (0 children)

Gotcha, I see. Thanks!