C# Functions Introduction


This entry is part 1 of 6 in the series C# Functions

The post C# Introduction lists all of the C# series of posts we have at this site. Often you have code that you need to run at several different points in your program. If you repeat that code in several parts of your program, that strategy will work but what if you need to make a change to the code? You will have to find all the places the code is run and be sure to make changes to each place. This is where functions come to the rescue. You can create a block of code that can be executed anywhere in your application. Now you have code that is reusable.

For example, you could have a function that returns the maximum value in an array. You can call this function from anywhere in your application. You don’t need to “re-invent the wheel”.

Signature

A function definition consists of a name, a return type and a list of parameters that specify the number and type of arguments that the function requires. The name and parameters of a function (but not its return type collectively define the signature of a function.

C# Functions: Function Multiply() and MultiplyIt()

class Program  // Functions Part 1
{
    static void WriteStuff() {
        WriteLine("from WriteStuff()");
    }
    static void Main(string[] args) {
        WriteStuff();  // call the function
        WriteLine (Multiply(3.4, 98.1));
        WriteLine(MultiplyIt(2.1, 3.5));
        ReadKey();
    }
    static double Multiply(double myVal1, double myVal2)
    {
        WriteLine("from Multiply()");
        return myVal1 * myVal2;
    }
    static double MultiplyIt(double myV1, double myV2) => myV1 * myV2;  
	// => Lambda is new in C# 6
}

Signatures are important to understand when working with delegates, for example. Delegates are important to understand before you take a look at lambda expressions.

Series NavigationC# Functions Part 2 Parameters >>