3.2 Methods
Welcome to the methods module. Throughout the course you will hear the term 'does stuff' quite a bit, through this module you will learn what we mean by that.
Objectives
Learn what a method is
Learn how to write a method
Learn why we need methods
File Location
Right click on your solution
Go to Add > New Project and select Console App (.NET Framework)
Name it
Methods
Description
A method is a group of statements that perform a task, or 'do something'. Every C# program has a class with a Main()
method. When your program starts up it will first look for this Main()
method.
Visualization
Access Modifier
Return Type
Name of Method
Parameters (What the method will bring in)
The return. What you want the method to do and what you want it to bring back.
Defining a Method
When you start to define a method in C#, you first declare the elements you will use in its structure. The syntax for a method will go like this: <Access Specifier> <Return Type> <Name of Method>(Parameters){Method Body (does stuff)}
Lets go over the elements real quick.
Access Specifier: Determines the visibility from a method class. Usually public or private.
Return Type: This is where you specify which data type to expect the method to return after it 'does stuff'.
Name: What you call the method
Parameter List: Enclosed between parentheses, this is where you will tell the method what data will be passed through.
Body: The set of instructions where you will tell the method to do 'stuff'.
Lets Try It
Underneath your
Main()
method, create a new method.It will have a return type of
int
Call it
Multiply
, and it will have two return parameters(int numOne, int numTwo)
Within the body, have a return of multiplying those two integers together
Then we call the method and give values to
numOne
andnumTwo
The answer will print to the console
Another One
Optional Challenge
Try creating a program that will have a user type in their first name, then their last name and use a method to join those names and print it to the console.
Challenge
Bronze Challenge
Create a
Netflix
class withproperties
of Name, Genre, and RatingCreate three objects from that class
Silver Challenge
Create a method called
GetSuggestion()
that returns different messagesIf the rating is 4 or higher, it should say something like "You should definitely watch this show."
The else message could be "You probably won't want to watch this show."
Gold Challenge
Create a list of objects based on the Netflix class
Write a foreach loop that would iterate over the loop and print the name, genre, and rating of each object
Answers
Next: Overloading Methods
Last updated