Page 1 of 1

C# Learning Series - Classes & Objects

#1 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5595
  • View blog
  • Posts: 11,970
  • Joined: 02-June 10

Posted 10 November 2012 - 10:46 AM

*
POPULAR

Learning C# Series

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


Is This A Good Question/Topic? 21
  • +

Replies To: C# Learning Series - Classes & Objects

#2 JimPickens  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 05-February 13

Posted 05 February 2013 - 02:18 PM

This is great for a beginner. Thanks for writing such easy to understand tutorials.
Was This Post Helpful? 0
  • +
  • -

#3 TommoUK  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 22-February 13

Posted 04 March 2013 - 09:16 AM

Have a lot of respect for the time you have put into your tutorials, Great work :)
Was This Post Helpful? 0
  • +
  • -

#4 acProgrammer  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 20
  • Joined: 23-March 13

Posted 06 April 2013 - 07:33 PM

This is good. I still will have to read it over a few times. Question: where do I learn more about the - get/set? I've seen this other places & have never used it. Of course, I am very new to programming & specifically c# but everything I get taught we use the toolbox and then build our code behind the object. Any feedback or suggestions would be great!


Thanks for your time ~ it is appreciated!
Was This Post Helpful? 0
  • +
  • -

#5 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9422
  • View blog
  • Posts: 35,405
  • Joined: 12-June 08

Posted 06 April 2013 - 09:27 PM

Typically the MSDN is a good place to start.

http://msdn.microsof...v=vs.80%29.aspx
Was This Post Helpful? 1
  • +
  • -

#6 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5595
  • View blog
  • Posts: 11,970
  • Joined: 02-June 10

Posted 07 April 2013 - 06:36 AM

Quote

where do I learn more about the - get/set?


Another good place would be the properties tutorial.
Its the very next one in the C# Learning Series.
Was This Post Helpful? 1
  • +
  • -

#7 scjohnson243  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 20-November 13

Posted 21 November 2013 - 06:20 PM

I just wanted to say THANK YOU for this tutorial - yours are some of my favorites, Much easier to understand than what I have been seeing all over the web and on the books I have bought.
I am a beginner, and I don't know if anyone else gets that feeling that your SO Close to a real understanding of the subject, I feel like I'm so close to getting it, and this tutorial is really helping...

Thank you again!
Was This Post Helpful? 0
  • +
  • -

#8 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5595
  • View blog
  • Posts: 11,970
  • Joined: 02-June 10

Posted 22 November 2013 - 06:22 PM

Glad to hear it helped
Was This Post Helpful? 0
  • +
  • -

#9 DADDYCARDONA  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 67
  • Joined: 04-July 10

Posted 26 November 2013 - 03:13 AM

This tutorial is so awesomely made. I took programming up many times, done Java, C++, VB and Cobalt in school, learned Javascript, PHP and other things but still have not understood it like this tutorial makes me understand it. You guys should teach programming in colleges because some of these teachers don't really teach they just use the outline for their students. You should teach in Phoenix Online classes :)
Was This Post Helpful? 0
  • +
  • -

#10 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5595
  • View blog
  • Posts: 11,970
  • Joined: 02-June 10

Posted 27 November 2013 - 06:58 AM

I appreciate the compliment. But I couldn't afford the pay cut to become a teacher.

Just remember - Colleges aren't in the business of getting students ready for the world. They are in the business of selling course credits. That's what they earn their revenue with. So the more courses you have to take the more money they make. Its good for them to stretch a year's worth of learning over 4 years.

Personally I'd like to a see a change in the business model. Professors should get paid 1% of each student's salary for the first 5 years after graduation. If they get the student ready for a good paying job then they make more money. Now that's incentive!
Was This Post Helpful? 0
  • +
  • -

#11 dsimer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 04-August 14

Posted 29 September 2014 - 09:18 AM

Fantastic. Thanks!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1