Classes and Objects
C#, VB.NET, JAVA, Objective-C and others are all Object Oriented Programming languages (OOP). Think about that. Object Oriented - meaning the language is Oriented around the use of Objects. Its not just a buzz word. Its the single most important foundation concept in the development of your programs, and your skills as a coder. Period. You can't think of it as an advanced concept that you're afraid of and will pick up later (after you establish lots of bad habits that will be hard to break).
Why is this important to learn about?
Its only the most basic of underlying principals upon which you will build all of your code for the rest of your career. Objects are what this entire language is Oriented around. If your code doesn't use them then its going to be a thousand times harder to do anything - if not nearly impossible. Making your code not follow established styles and technology is going to hinder you and make your code something that no co-worker or employer will want to deal with.
Terms you should be familiar with:
Spoiler
Note: All examples were created using Visual Studio 2012, targetting the .NET Framework 4.5, using a WPF project. We'll do our best to point out anything that might not work in older versions or ways of using the same techniques in WinForms.
Classes and Objects
For those just looking for a quick block of code as an example or reference (which we all do from time to time) here ya go
Spoiler
Objects and Classes aren't scary
I don't really care what your classmates said. I don't really care if you went "huh?" when you read the description of a class on MSDN or in your textbook. These are easy and I'm going to present this for you in an easy to pick up way. So stop, breathe and relax. You've got this.
The reason objects aren't scary is because they aren't new to you. You've been dealing with objects since you were a baby. Remember that first playtoy where you put the cubes through the square holes and ball through the round hole? Well those are objects. You're reading this tutorial on an object: A monitor. Which is connected to another object: A computer. Which is made up of lots of smaller objects: Cards, drives, case, fans.
Its no accident that objects in code seem to mimic objects in the real world. Its on purpose because we already understand them, and because we tend to code for things that are in the real world. So if you are coding for the real world it makes sense to follow the same patterns. So as you can see, objects aren't new or scary. You've used them your entire life. This article is going to show you how to build them in C#. Easy peezey.
If you didn't read the term definitions above, read them now. The key points are:
- class - The blueprint for an object, but not something your code will interact with.
- object - The instance built on the class blueprint. This is 'physical' thing you interact with like the actual house that was built according to the blueprints.
Good program design dictates that objects be as unaware of the details of each other as possible. They should be 'black boxes'. You put something in, you get something out. But what happens inside the box is none of your business so long as you get what you expected. The reason for this is so your program is robust - it doesn't break and crash just because you made a simple change inside one of those black boxes. If you think of your program as a castle built out of Lego blocks then each block is a class. It doesn't know much about the block its connected to. The only thing that one block needs of the other is a common interface so they can connect: The dimples on the top and matching holes in the bottom. It could be 6 dimples long or 4. It could be blue or red but that won't affect the operation. If you stack 3 Lego blocks on top of each other you have 3 layers of code where the first layer is totally unaware of the third layer. The second layer has the job of binding the two together. Same with your code. See, I told you this object stuff was child's play.
C# classes can contain (amongst other constructs):
- Fields
- Properties (The characterists of a thing)
- Methods (The actions of a thing)
- Events (The notifications announced by a thing)
- Other classes. (Just like an engine also contains piston)
This is how they are able to be mostly self-contained. They hold data, manipulate data and so on all within themselves then they just hollar out the results when they are done (raise an event).
Look at the world as objects. Everything you look at you should be able to code in your head. A garden hose
Properties: Length, color, material, diameter, IsConnected
Methods: None really as a hose doesn't really 'do' much.
A Bycycle
Properties: Color, brand, NumberOfGears
Methods: ChangeGear(int GearNumber), ApplyBrakes, ReleaseBrakes
When you see the world as objects then writing code for them is almost so easy its boring.
I think the best way to understand something is to see it in action and to actually build something from the ground up, so let's look a common homework assignment that every student sees and study it for how we can build the application in an O.O. (Object Oriented) way. Along the way we will look at the common non-O.O. way this gets approached so we can see how much harder life gets when you don't do it the right way.
The assignment:
Build an order taking program for a pizza place. The customer should be able to pick any kind of crust, a variable number of toppings, include sales tax and tip, calculate the total.
The wrong (non-O.O.) way.
Jump on the keyboard and start banging out stuff that was covered in the most recent chapter of a book. Build an array of crusts, an array of toppings, an array of prices. Try to keep everything syncronized: If I pick the 5th element from the ToppingsArray[] I need to use the 5th element from the PricesArray[]. Hopefully nobody ever adds a new topping and gets things out of order. A couple hours in start wondering how you make a management list of ordered items and their prices. Wonder how to take these disperate arrays and offer a good looking GUI for the user. Realize you've just painted yourself into a corner. But at least you jumped onto the keyboard right away so you could get to this point faster.
The OOP way
Stop. Think. Plan. Visualize an actual pizza place. What are the real-world objects you have to deal with and how can you see them in a logical and hierarchical way? Start drawing and planning on your whiteboard.
Let's see... There are ingredients for a pizza that include crusts and toppings. Ok, that sounds like objects, right? And a group of ingredients make up a pizza. Then again alot of pizza places also do pasta and a group of ingredients also make up a pasta dish. So its fair to say a group of ingredients make up a dish the customer orders and that pizza and pasta are types of dishes. Hey, look at us: We're designing hierarchical classes that inherit from each other just like in the example at the top of the page.
Spoiler
What did we say about a Dish? That it contained Ingredients. I guess we should make an Ingredients class so we can include a collection of them in our Dish. We know that the ingredients for a pizza each have a cost associated with them because those ingredients are the toppings and the crust. Maybe certain crusts cost more.
Spoiler
Notice how this stuff practically codes itself if you just think it through then make your code objects mimic their physical counterparts in real-world? Because Pasta and Pizza are classes derived from Dish they inherit the properties and methods of Dish. So we don't have to duplicate the Name and Price properties of Dish inside Pizza and Pasta: They inherit these.
Both Pizza and Pasta will need to supply a total cost. So we need a method for calculating the total. But lets think ahead. Its possible that one day there will be different rules for how to calculate the totals. Planning ahead for unforseen changes is one of the hardest skills in development and really only comes from experience learned by NOT planning first. Maybe the cost of the ingredients for a dish of pasta are less than the cost for those same ingredients on a pizza because there are less of them in a bowl of pasta than on a 24" pizza.
What have we figured out here? All Dishes and their children need a Total() method, but each child needs to have its own version of that method. This is where the matched pair of statements virtual and override come in. Any method marked as virtual in the parent (base) class can be overridden in the child (inherited or derived) class. Take note of line 9 in the base Dish class and line 27 in the inherited Pasta class. The base is marked virtual the inherited override.
Spoiler
So what we have is a the base Dish class calculates the total using the full value of the ingredients. Since that is the rule we want to follow for a Pizza we don't have to override anything: We'll just call the existing Total() method. But for the Pasta class we override Total() to multiply each ingredient price by .75, giving us a 75% reduction in the cost of those ingredients.
What other objects do we have to deal with for this program? Oh yeah, the order itself. What are the objects in an order? You see this every time you order a pizza: Its the stuff on the ticket that the counter guy wrote up. Well, there are several Dishes, and tax and tip and customer name and server name etc. Let's stub out all of that.
Spoiler
At this point we practically repeat for the order what we did for the Dish. Make a loop that goes through all the LineItems (which is just a list of Dishes) and total them up. That would be the subtotal. Then we can take that, calculate the tax, and the take to the subtotal and we have the GrandTotal. For fun and just to show the difference between a property and a method Tax is a read-only property that does our calculation for us. We can use this just like any other variable. Since it has no set{} method, it is read-only. For more on properties check out the properties article that is part of this learning series.
Spoiler
In Conclusion
Master Spliter to the Turtles said:
Possess the right thinking.
As long as you think in terms of "How small and self contained can I make these little Lego blocks of code?" you'll do well.
See all the C# Learning Series tutorials here!
This post has been edited by tlhIn`toq: 10 November 2012 - 11:12 AM





MultiQuote





|