C# Function: Parameter, Variable Scope, and Main Function or Method


C# Function- it is a tool that allows you to execute some parts of the code in an arbitrary place applications.

For example, we can write a C# function that searches for the maximum smallest element of the array. As a result, it will be possible to use this C# function from an arbitrary point in the program, and in each case, same lines of code. Since we only have to write this code once, then the changes that need to be made to it will affect all numbers wherever this code is used. Such a C# function can be represented yourself as reusable code.

Advantage of C# function:

C# functions also have the advantage of making the program more readable, and we get the ability to group together. parts of programs that are logically related to each other. By doing so, you can but to make the body of the application itself small, since the solution of the internal tasks of the application will be carried out separately. This is similar to the way that in VS (visual studio) you can connect different pieces of code using the mode outline view of programs, which allows you to attach a more logical structure.

The C# functions can also be used to create multipurpose programs, which perform the same operations on different data. We have the ability to transfer information to functions with which they need to work, in the form of parameters and receive the results of the C# function in the form of returned values. In the example above, you can pass the function as a parameter to the array to be searched, and get an element of the array with the maximum value as the return value. This implies, that we can use the same C# function each time to work with different arrays. The parameters and the return value of a function are collectively referred to as the signature of the C# function.

How to create and use the C# functions:

This section explains how you can enable features into applications, and then use (call) them from the code. First there will be considered simple C# functions that do not exchange data with the caller code, and then we move on to more complex use of C# functions. So let’s start right away with an example.

Create a new console application named Function and press ok button

C# Function

Add the following code to Program.cs:

Run the program:

C# Function

Program Explanation:

The next four lines of code describe a simple C# function called write:

The code contained in this C# function simply displays some text in the console window. However, this is not so important, since at the moment we more interested in the mechanisms underlying the description and use of function name.

In this case, the C# function description consists of:

Two keywords: static and void

The name of the function followed by the parameters: Write()

A section of executable code enclosed in curly braces.

The code used to describe the write() function looks almost like this the same as the code of the application itself:

This is because all the code that we have created so far (apart from descriptions of types), is a part of some function. This C# function  Main() performs the function of the console entry point new application. When an application written in C# starts up, what happens is calling the entry point function it contains, and when that C# function ends its work, the execution of the application is interrupted. Any executable code written in C# must have an entry point.

The only difference between the C# Main() function and the write() function (apart from those lines of code that they contain) is that in parentheses There is some code behind the name of the Main function. This code serves to set parameters; we will return to a more detailed discussion of it a little later.

As mentioned earlier, both C# functions – Main() and write about – describe are defined using the keywords static and void (absent). The keyword static has to do with object-oriented concepts. programming, we will move on to its consideration below. At this stage from you only need to remember that all the C# functions that will be involved in the applications of this section, be sure to use this key your word.

The void keyword, on the other hand, is very easy to explain. It indicates that the C# function does not return any value. what needs to be written in cases where the C# function has a return value reading. Continuing to look at our application, we find code that makes a function call:


It consists of the function name followed by empty parentheses. When program execution reaches this point, the code contained in the Write() FUNCTION will start executing.

Return Values in C# Function:

The easiest way to exchange data with C# functions is to use return desired value. C# functions that use return values have a numerical value in exactly the same way as any variables used when evaluating expressions. Similar to variables, return values are of type.

For example, you can describe a function named getstring() that returns a value which will be of type string, and use it in your program:

Alternatively, you can define a C# function called getval() that will be rotate a double value, and use it in a mathematical expression:

If the C# function have a return value, then it is necessary to add These two changes:

  • In the function description, instead of the void keyword, specify return type.
  • After completing all calculations in the function, use return keyword and pass the return value calling code.

Code syntax for the considered type of console application functions will look like this:

The only limitation in this case is the requirement that WHAT <ReturnValue> MUST be TYPE <ReturnType> OR MUST it is possible to implicitly convert it to this type. Generally speaking, <returntype> can be anything, including the most complex types. In the simplest case, it might look like this:

However, in real life, the return values ​​are usually the product some computations performed by the function, since the same result can be achieved simply by using a const variable.

When a return statement is reached during program execution, control is immediately transferred back to the calling code. No lines of code after this operator will not be executed. From this, however, it does not at all follow that in the body function, the return statement must be the last. He can be used before, for example, when branching by some condition. Including a return statement in a for loop, in an if block, or in some other structure will immediately terminate the execution of both this structure, as well as the whole function. For example:

In this case, one of two values ​​will be returned – depending on the values ​​of the checkVal variable. There is only one limitation: the return statement must be executed before how the closing curly brace} of the given function will be reached. Following the code is not valid:

If checkval > = 5, then no return statement will be encountered, which is prohibited. All branches must end with this statement.

Note: the return statement can be used in C# functions declared using the void keyword (they lack any return value). In such cases, the C# function simply stops working. Therefore, when using the return statement, it is an error to place the return value between the return keyword and the point following it with a comma.

C# Function Parameters:

If the C# function is to receive parameters, then it is necessary to set:

  • The list of parameters accepted by the function in its description, as well as the types of these parameters
  • Matching parameter list on every C# function call

Syntax of Function Parameter:

There can be an arbitrary number of parameters, for each of which you can specify type and name are given. Use commas as a separator between parameters. Each of the parameters is available inside this C# function as a variable. For example, the following simple C# function takes two double parameters and returns their product:

Now let’s move on to a more complex example.

How to pass parameter to a C# function:

Create a new console application named Parameter and press ok.

C# Function

Add the following code to Program.cs:

Run the program:

C# Function

Programming Explanation:

The C# function takes as a parameter an array of whole numbers and rotates the greatest of them. Its description is as follows:

This C# function, Maxvalue(), has one parameter, which is described as an array of type int called intArray. The return value is also int. Determining the maximum value is not difficult. local integer variable named maxVal as an initial value the first element of the array is matched and then. compares this the values ​​are consistent with all other elements. If the current item is greater than the value of the variable maxval, then the current value of maxVal is replaced is set to this value. When the loop is finished, the variable maxval contains the largest value of the given array, which is returned by the operator return.

The code located in Main() declares and initializes a simple integer an array to be used in conjunction with the Maxvalue() function:

When calling the C# function Maxvalue, the value is assigned to the Maxval variable of type int:

then we display this value on the screen using console.writeline()

Matching parameters in C# Function:

When calling a C# function, its parameters must exactly match its description. It is necessary to match the types of parameters, their number and their order giving. This means that, for example, a C# function:

cannot be called using the line:

In this case, we are trying to pass a double value as the first parameter, and a string value as the second, which does not match the order in which these parameters appear in the function description. You cannot use this line either:

since only one string parameter is passed in it instead of two required parameters.

Attempting to use either of these two lines to call a C# function will result in a compile-time error, since the compiler imposes the exact matching the signatures of the called functions. Returning to the previous example, such a requirement means that the C# function Maxvalue() can only be used to get the maximum integer from an array of integers. If we change the code in Main about as follows:

then such code will not go through the compilation procedure due to the wrong type of the parameter.

Parameter arrays in C# Function:

C# provides the ability to set one (and only one) special function parameter. This parameter, which must be located the latter is known as the parameter array. It allows you to use a variable number of parameters when calling C# functions. The parameter array is described using the params keyword.

Parameter arrays serve as one way to simplify your code because thanks to them, you do not have to pass arrays from the calling code. On the contrary, you can pass several parameters of the same type, which are placed in an array for later use inside the C# function. When describing a function with an array of parameters, the following code is used:

In order to call this C# function, you need the following code:

In this case, <value1>, <value2>, and so on are TYPE Values ​​<type>.

They are used to initialize an array named <name>. There is no limit to the number of parameters that can be specified here; the only requirement for them is that they should all be one of type <type>. It is possible not to specify any parameters at all.

This last feature makes parameter arrays useful, in particular when giving some additional information to use function. For example, suppose you have a getword() function that will takes a string as the first parameter and returns the first word from this line:

The variable firstword will be assigned the string “This “. We can add a params parameter to the getword() function, which will allow select and return another word by its index:

If we proceed from the assumption that word numbering starts from 1, then as a result of such a call the firstWord variable will be assigned the string “is” . You can limit the number of characters returned by entering a third parameter, which is perfectly acceptable for the params parameter:

In this case, the string “sen ” will be assigned to the variable  firstword. Let’s look at the example in full.

How to pass parameter array in c# function:

Create a new console application named ParameterArray and press ok button.

C# Function

Add the following code to Program.cs:

Run the program

C# Function

Programming Explanation:

In this example, the C# function sumVals is described using the params keyword, which allows it to take an arbitrary number of int parameters. (and no other):

The code in this C# function loops through all the values ​​in the vals array and sums them up, returning the resulting result. We call this C# function from Main with five integer parameters:

However, you can just as well call this function by passing zero, one, two or one hundred parameters of an integer type: there is no limit on the number of parameters to be specified.

Passing parameters by reference and by value in C#:

All previous c# functions used parameters passed by value. In other words, we passed the value into a variable, which then used inside a function. Any changes that this variable underwent within the C# function had no effect on the parameter used when the C# function was called. As an example, consider a function that doubles the parameter passed to it and prints the result to the screen

In this C# function, the passed parameter is doubled. If we call this function like this:

then the output on the console will look like this:

Calling the showDouble() function with the myNumber variable as a parameter is not has no effect on the variable myNumber described in Main, although the parameter to which it is assigned is doubled.

This is all well and good, but if we want the value of the variable myNumber has been changed, there will be a problem. Of course, you can use the C# function which returns the new value of the variable myNumber, and call it as follows in such a way:

However, such code is quite difficult to understand; moreover, this method does not allows you to reflect changes in the values ​​of variables used as parameters (since C# functions always return only one value).

Instead, pass the parameter by reference. This means that the function will work with exactly the variable that was used when calling a function, not a variable that has the same meaning. Therefore, any changes to the variable used by the C# function will affect the value variable used as a parameter. To do this, when describing the parameter, you must use the ref keyword:

Secondary ref keyword must be used when calling C# function (this is a mandatory requirement, since the fact that the parameter is described as ref, is an integral part of the function signature):

In this case, the following text will be displayed on the console:

this time changed myNumber in the C# function  Showdouble(). for variables used as parameters of type ref, there are two restrictions. first, since there is a possibility that as a result of when the C# function is called, the value of the parameter called by reference will be changed, then when a function call is prohibited from using const variables. from here it follows that the following call is invalid:

Second, you need to use a pre-initialized variable. C# does not guarantee that a parameter of type ref will be initialized by that function in which it is used. The following code is also invalid:

Output parameters in c# Function:

In addition to being able to pass parameters by reference, we can indicate that this parameter is an output: in the description of such a parameter the out keyword is included, used in the same way as the ref keyword (as a parameter modifier in the C# function description and when calling the function). In fact, this method provides almost the same capabilities as transfer parameters by reference, in the sense that the value of the parameter after execution function gets into the variable used when calling this C# function. There are, however, significant differences. While using a variable; which is not assigned an initial value, is not allowed as a parameter of type ref, it can be used as an out parameter. Moreover, a parameter like out will be treated as having no initial value by the function itself, in which it is used. This means that although passing a variable that some value is assigned, as a parameter of type out is valid, however, during the execution of the C# function, the value stored in this variable will be lost.

As an example, consider extending the maxvalue() function, which returns the maximum value in an array. Let’s modify this C# function

This C# function can be used like this:

The result of its execution will be the following:

An important point to pay attention to is the need to the ability to use the out keyword when calling a function (as well as the word ref).

Variable scope in C# function:

As you read the previous section, you may have wondered why need to exchange data with functions. The answer is that in C# variables can only be accessed from certain areas code. It is customary to say that a variable has a certain scope, within which it is available. Variable scope is a very important concept that is best illustrated with an example.

what is variable scope and how to use it:

Create a new console application named ScopeVariable and press ok button.

C# Function

Add the following code in Program.cs

Compile the code and notice the error message and the warning that will appear in the list of tasks in my case the error is:

Program Explanation:

So what’s wrong in this case? And the fact that the variable myString, described in the main body of the application (in the Main() function ), turns out to be inaccessible In the Write() function. The reason for this unavailability lies in the fact that the variables have a scope, within which their use is permissible. This area extends to the block of code in which they are described and to all code blocks directly nested within it. C# function code blocks are separated from code blocks of which they are called. Therefore, inside the write C# function, the name myString is not counted defined, and the variable myString, defined in the Main() function, is out of scope: it can only be used within the Main() function.

variable scope Example2

In fact, in the write() function, we could have used a completely different myString variable. Try to make the following changes to the program:

This code successfully passes the compilation procedure and produces the following result:

C# Function

Program Explanation: This program does the following:

  • The Main() function defines and initializes the variable Named myString
  • The Main() function transfers control to the write() function.
  • The write() function defines and initializes the variable Named myString, and is different from variable Named myString, described in function Main().
  • The write() C# function prints to the console a string containing that value the variable mystring, which is assigned to it in the write function.
  • The write function returns control to the Main() function.
  • The Main () function prints to the console a string containing that value The variable myString, which is assigned to it in the function of Main().

local and global variable scope in C# function:

Variables that are only scoped to one C# function are called local variables. It is possible to describe global variables whose scope covers several functions at once. Submit the following changes to the program:

In this case, the following result will be displayed on screen:

C# Function

Program Explanation:

This time, we have included in the code another variable named myString by changing hierarchy of names in the program. This variable is described as follows:

Note that we needed to use the static keyword again. We will not go into details: at this stage, it is enough to know that for console applications of this type in the description of global variables be sure to use either the static keyword or the keyword const words. If we plan to change the value of a global variable, then the static keyword is required, since const forbids any changing the value of a variable.

To distinguish a global variable from a local variable with the same name in the Main() and write() functions, we need to classify a global variable name using the fully qualified name.

In this case, we refer to the global variable called Program.myString. Please note that this only needs to be done in the event that there are global and local variables with the same name; if a local variable named myString did not exist, then we could use NAME myString instead of Program.myString to refer to the global variable. when it is used a local variable whose name is the same as the name of a global variable, the global variable is said to be hidden.

The value of the global variable is set in the Main() function:

and is used in the write() function:

Now you’re probably wondering why we don’t always resort to this. way of communicating with C# functions. Indeed, there are certain situations when this method of data transmission turns out to be more preferable, however, there are no fewer (if not more) situations when it is less than convenient.

Whether or not to use global variables depends on how you use each specific C# function. The problem with global variables is that, by and large, they turn out to be unusable for functions. “general purpose” that are able to work with any transmitted to them data and are not limited to data specified by a specific global variable.

Parameters and return values versus global data in C# function:

This section is devoted to a more detailed examination of data exchange with the C# function through the mechanism of global variables and through the mechanism of parameters and return values. Recall that we are talking about the differences between the two programs. The first of them looks like:

C# Function

The second program looks like this:

C# Function

programs Explanation:

The results of the execution of both programs are completely identical.

It should be noted that there are no hard and fast rules determining the preference of using one method over another: both of these methods are perfectly valid. However, there are some considerations which it is desirable to consider when choosing one of them.

First, note that (as noted above) the version a showDouble() function that uses a global value can only use the global value of the val variable. Application of this version functions forces us to use this particular global variable, which somewhat limits the flexibility in the use of this C# function and requires constantly copying the value of a global variable to other variables, including ‘in case it is necessary to save the result. Also, global data can be changed elsewhere in the application, resulting in unpredictable results (we can recall that the values changed, too late).

However, this loss of flexibility is often an advantage. Exist situations when the use of a C# function is planned exclusively for one specific purpose and the use of globally described data reduces the probability that we will incorrectly access the C# function, for example, by passing incorrect parameters.

Of course, this simplicity actually makes the program less understandable. By explicitly specifying parameters, you can see exactly what is being changed, even with a quick glance at the C# function. If a C# function call is encountered, having the form myFunction (val1, out val2), then it immediately becomes clear that follows pay close attention to the variables val1 and val2 and that the variable vai2 will be assigned a new value at the end of the function execution. Conversely, if this C# function does not have any parameters, then we cannot make assumptions about what data it is manipulating on.

Finally, remember that using global data is not is always possible. Next, we will see examples of programs stored in different files and / or belonging to different namespaces that interact with each other through the use of functions. Such cases, the code often turns out to be so divided that it is not clear where exactly should global variables be stored.

So, both methods of data exchange can be used with equal success. In most cases, we will insist on using parameters instead of global data, however, there are some situations when it may be more appropriate to use global data; and already, in every way case, this method is not an error.

C# Main() function:

Now that you are familiar with almost all of the simple ways to create and use functions. Let’s take a closer look at the Main() function.

As mentioned earlier, the Main function in c# is the entry point to the application. in C# the execution of this function spans the execution of the application. This C# function has a parameter  string [] args, but so far we have not described it. In this section, you will get acquainted with this parameter and find out how way it can be applied.

There are four different signatures, which can be used for the Main() function:

  • static void Main()
  • static void Main(string[] args)
  • static int Main()
  • static int Main(string[] args)

The args parameter of Main() is a method that allows an application to receive information from the outside that is specified during its execution. This information takes the form of command line parameters. You’ve probably come across command line parameters before. When the production the application is launched from the command line, then very often there is the ability to directly set some information, such as a name the file that is required to be loaded to run the application.

As an adjunct measure let’s take a look at Windows Notepad application. You can run it, just by typing notepad either in the command prompt window or in the window, which appears when you select Run from the Start menu. However, in these same windows, we can type something like:

notepad “myfile.txt”.

As a result, Notepad will either load the file myfile.txt, or, if there is no such file exists, will offer to create it. In this case, “myfiie.txt” is the command line argument. We can write a console application ourselves, which will work in a similar way using the args parameter. When the console application is launched, then all the specified command parameters are strings are placed in the args array. In the future, these parameters can be used be called as needed. Let’s look at an example of how to do this.

How to run command line arguments program in C# main() function:

Create a new console application named MainFunction and press ok button.

C# Function

Add the following code to Program.cs:

how to run command line arguments program:


Open the property pages project (for this you need right click on the project name in my case the project name is MainFunction in the Solution Explorer window and in the drop-down menu select Properties and open by double clicking) .

C# Function


Select the Configuration page Properties | Debugging and add to the Command Line installation Arguments (see picture below) those command line arguments, whatever you want.

C# Function


run the application:

C# Function

Code Explanation:

The code used in this case, very simple:

We use the args parameter in exactly the same way as we would use any other string array. We don’t do anything special with arguments, we just display everything that was set on the screen.

In this example, the arguments are set through the Project Properties dialog in VS(visual studio). This is a convenient way to use the same arguments every time you run. applications from VS: otherwise you would have to type them in the command line every time you start the application. The same result can be achieved by opening a command line window in the directory where the output is carried out output stream of the application in my case the address is C:\Users\Shahzada Fawad\Documents\visual studio 2012\Projects\MainFunction\MainFunction\bin\Debug),


C# Function

and typing the following text and press enter button:

MainFunction 256 myFile.txt “a longer argument”

C# Function




Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button