Parameters - Global Variables

From TRCCompSci - AQA Computer Science
Revision as of 20:10, 17 December 2016 by Mohkale (talk | contribs) (Basic Example)
Jump to: navigation, search

When a variable needs to be passed into a subroutine, this is done through the use of parameters. The subroutine can then use these parameters to execute its code. Parameters should be written inside the subroutine brackets, along with their variable type. In addition, multiple parameters should be separated by commas (",").

General Concept Example

 1 namespace Project
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             greeting("Geoff");
 8             greeting("Bob");
 9         }
10 
11         static void greeting(string name)
12         {
13             Console.WriteLine("Hello, " + name);
14         }
15     }
16 }
17 //Output:
18 //Hello, Geoff
19 //Hello, Bob

Scope

parameters passed to a function are passed as copies of their actual values and hence values sent and used as arguments by method are from a memory point of view different to the values actually passed. Because of this any changes made to arguments passed to a method have no affect on the value of the actual variable they're passed from, for example:

 1 class Program {
 2     public static void DoSomething(Object arg1) {
 3         (int)arg1 += 1;
 4     }
 5 
 6     public static void Main(String[] Args) {
 7         int test = 1;
 8         Console.WriteLine(test); // Outputs 1;
 9 
10         DoSomething(test);
11         Console.WriteLine(test); // Outputs 1;
12 
13         test += 1;
14         Console.WriteLine(test); // Outputs 2;
15     }
16 }

Type Passing