Comment
Author: Admin | 2025-04-28
Make all of the bunnies look the same!Using MethodsThe code starts to get a little more disorganized with each additional bunny. There is a lot of repeated code that does the exact same thing, and it becomes difficult to maintain. Luckily, methods can make this code better!A method is a block of code that runs when it is called. This allows developers to reuse code; they can define the code once, and use it many times.QuestionsQ: Where is there already a method in the program?A: The Main method! This is the entry point for the exeuction of a C# program.Q: For this program, what kind of method could help simplify the code?A: How about a method to draw a bunny!Defining the MethodUnder the Main method (after the }), start defining the method with public static voidThese keywords set certain things about the method. They are outside of the scope of this lessonAdd the name of the method: DrawBunnyAdd parentheses and curly brackets (() {})Click in between the opening and closing curly brackets and press the Enter keyIn the body of the DrawBunny method, add the code to draw a bunny!public static void DrawBunny() { Console.WriteLine(" () () "); Console.WriteLine(" (^ ^) "); Console.WriteLine(" (___) "); Console.WriteLine();}Calling the MethodRemove all of the bunny-drawing code from the body of the Main methodBe sure to keep the console color code though!Call the DrawBunny method in the code with DrawBunny();Add a few additional method calls under the first oneClick the "run" button to run the code and see the bunnies appear!Adding WhiskersOne of the best things about methods is that if a developer wants to update code, they only have to do it in one place. For example, to add whiskers to the bunny, it is only necessary to change one line of code instead of several. This change will apply to every method call!In the DrawBunny method, find the line that draws the bunny's faceAdd a greater-than sign (>) on the left side of the bunny's faceAdd a less-than sign () on the right side of the bunny's faceClick the "run" button to
Add Comment