[edit] Intro to C# Functions
C# Code that must be executed many times is a good candidate for functions. For Example, if you have to perform some operation that required you to cut and paste the same code over and over again can get pretty tedious. Also, C# function can provide a centralized location for common information. This way if you have to change common code you do not have to search and replace text in your code, you can just change the code in the function.
Lets see a programming example:
The following example will find out which number is bigger or if the numbers are equal.
using System;
class Program
{
static void Main(string[] args)
{
int x, y;
x = 8;
y = 1282;
if (x < y)
Console.WriteLine(y + " is bigger");
else if (x > y)
Console.WriteLine(x + " is bigger");
else
Console.WriteLine(x + " and " + y + " are equal");
////////////////Prints 1282 is bigger//////////////
x = 90;
y = 34;
if (x < y)
Console.WriteLine(y + " is bigger");
else if (x > y)
Console.WriteLine(x + " is bigger");
else
Console.WriteLine(x + " and " + y + " are equal");
////////////////Prints 90 is bigger/////////////////
x = 1029465;
y = -1283;
if (x < y)
Console.WriteLine(y + " is bigger");
else if (x > y)
Console.WriteLine(x + " is bigger");
else
Console.WriteLine(x + " and " + y + " are equal");
////////////////Prints 1029465 is bigger/////////////
x = 34;
y = 34;
if (x < y)
Console.WriteLine(y + " is bigger");
else if (x > y)
Console.WriteLine(x + " is bigger");
else
Console.WriteLine(x + " and " + y + " are equal");
////////////////Prints 34 and 34 are equal///////////
Console.ReadLine();
}
}
Output:
1282 is bigger
90 is bigger
1029465 is bigger
34 and 34 are equal
As you can see the if/else if statements are copied and pasted each time x and y changed. There is a more effiecient way to do this. Just image if that common code were hundreds of lines and you had to edit some part of that common code. We will you to C# functions in the next section
|