To begin, let's start with a blank program. Then we will create a new class outside of our "Program" class and we will call it "Customer". Further, we will create public variables Course and isVegetarian in order to distinguish what types of orders we will be dealing with. The idea here will be to determine how much a customer owes a restaurant for an order that is made. We will keep it simple and give customers two options for Appetizer and Entree, being vegetarian, and non-vegetarian.
In order to figure out what we will need to set our price to, there has to be methods within the Customer class that tell the cooks what to serve, and the cashier how much a customer owes. So we will create two methods in Customer which can be called from our main program class that do these tasks. Code to create this class is shown below:
Note the use of the "this." within the methods. This shows that there must be values being brought into the Customer class to help the program function. So we can see that a non-vegetarian item will cost more in all cases. While entrees are the more expensive than appetizers, as we would assume.
Now this can all be simply placed below our main Program class. There is no need to open up another tab or anything of that sort like we would do in Eclipse. We can do this all from one window, helping us see everything that will be happening once we run the program.
So we have the Customer class variables and methods ready to go. Now we must create instances of this class within our main Program class.
In order to accomplish this task, we will have to use the syntax that we are familiar with of
Then, we must set the values for the variables in our Customer class in order for the methods to work the way we would expect. A quick way to do this is to initiate these items using this syntax:
Now that these values are set, we can create print statements to tell us the order, and their value:
Note the use of "{int}" and "{0:C}" in the print statements. This is a way of interpreting strings to print. The 0 and 1 will be the location of the course and vegetarian preference, while the 0:C converts the value of the order to dollars.
So we will create a few more instances of the Customer class in Program to produce other menu items, and the output will appear as such below:
Now this is a relatively basic example of how to use methods in C#, but it is more than enough to get you started with creating your own. These can become as simple or as complex as you like, and it provides us with the ability to do much more with our programs more efficiently.
No comments:
Post a Comment