Here is the code we did in class for Methods.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace methodsexample
{
class Program
{
//this is a class level variable
//a variable has the "scope" of the block
//it is declared in--the class
//That means age can be seen and accessed
//by any method in the class
int age = 0;
static void Main(string[] args)
{
//because Main is static it is loaded into memory
//immediately, but the rest of the class is not
//this line loads the rest of the class into memory
Program p = new Program();
//this calls the method "Hello." To Call a method just
//name it and pass any parameters
//p is our variable standing for the class Program
//p.Hello() means the method belongs to the Program class
p.Hello();
//call Pauseit
p.PauseIt();
}
//void means it doesn't return anything
//it just does its stuff and returns
//to where it was called
void Hello()
{
Console.WriteLine("Hello");
//call the method GetName()
GetName();
}
void GetName()
{
Console.WriteLine("What is your name?");
string person=Console.ReadLine();
//call the method getAge() and pass it the string parameter
//person
GetAge(person);
}
//this method takes an argument or Parameter
//of the type string
void GetAge(string nom)
{
Console.WriteLine("What is your age?");
//age has class scope. It is important to not
//re-declare it here by saying "int age"
//if you do C# gives the local variable precidence
//and the class level age will not get a value
age = int.Parse(Console.ReadLine());
//calls the Method HowIsItGoing() and passes
//the parameter nom
HowIsItGoing(nom);
}
//This method returns a value of the type int
//Any method that returns something other than void
//must have a return statment that returns
//a value of the kind indicated
int GetBirthYear()
{
int years = 0;
//use the built in DateTime class to get the year
int currentYear = DateTime.Now.Year;
//subtract the age from the current year
years = currentYear - age;
//return the resulting value
return years;
}
void HowIsItGoing(string name)
{
Console.WriteLine
("You are {0} years old. How's it going, {1}?",age, name);
//this calls the GetBirthYear() function and store the value
//it returns in the variable birthYear
//if you don't assign the returned value to a variable
//it just goes away
int birthYear = GetBirthYear();
Console.WriteLine("you were born in {0}", birthYear);
}
void PauseIt()
{
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
}
No comments:
Post a Comment