Thursday, August 4, 2011

Methods--First Take

Methods are blocks of code that do something. Ideally you should break up your code into seperate methods, each of which does just one thing. This makes the program easier to debug and manage.

A basic method signature follows this pattern

[accessability][return type] [method name](parameters if any)
{
}

Here is an example of a simple method that returns nothing(void) and takes no parameters.

private void PrintName()
{
Console.WriteLine("Enter your name");
string name=Console.ReadLine();
Console.WriteLine("Hello {0}",name);
}

Here is an example of a method that returns an integer and takes a parameter.

private int Cube(int x)
{
return x*x*x;
}

A method that has a return type other than void must have a return statement.


Calling methods


Methods must be called to be run. Below is a brief program that uses the cube method and another void method called GetValues(). The program is heavily commented.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CubeMethodex
{
class Program
{
///
/// this program demonstrates basic
/// examples of breaking a program
/// into seperate methods
///


static void Main(string[] args)
{
//because main is static
//you must initialize the class
//to access its methods
Program p = new Program();
p.GetValues(); //call the method
p.PauseIt(); //call the method
}

//the private means the mehtod can only be
//accessed from within this class
private void GetValues()
{
//prompt the user for a value
Console.WriteLine("Enter an integer Value");
//get the value and use the Parse method of int
//to convert it to an integer
int number = int.Parse(Console.ReadLine());
//write the number {0}, then call the cube
//method passing it the number
//output the result returned by the
// method {1}
Console.WriteLine
("The cube of your number {0} is {1}",
number, Cube(number));
}

private int Cube(int x)
{
//the number in the previous method
//is mapped to x
//return the result as an int
return x * x * x;
}

private void PauseIt()
{
//a method to pause the console
//long enough to read it
Console.WriteLine("Press any key to Exit");
Console.ReadKey();
}
}
}



Notice how main calls GetValues() and the GetValues() method calls Cube() passing it the number provided by the user. Each method does one basic thing. If something goes wrong you know where to look.

No comments:

Post a Comment