C# Function: Parameter, Variable Scope, and Main Function or Method
Description:
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
Add the following code to Program.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Function { class Program { static void Write() { Console.WriteLine("This is Write function."); } static void Main(string[] args) { Write(); Console.ReadLine(); } } } |
Run the program:
Program Explanation:
The next four lines of code describe a simple C# function called write:
1 2 3 4 5 6 7 |
static void Write() { Console.WriteLine("This is Write function."); } |
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:
1 2 3 4 5 6 7 8 |
static void Main(string[] args) { } |
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:
Write();
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:
1 2 3 |
string = myString; myString = getString(); |
Alternatively, you can define a C# function called getval() that will be rotate a double value, and use it in a mathematical expression:
1 2 3 4 5 |
double myVal; double multiplier = 5.3; myVal = getVal() * multiplier; |
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:
1 2 3 4 5 6 7 |
static <returnType> <functionname> () { return <ReturnValue> } |
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:
1 2 3 4 5 6 7 |
static double getVal() { return 3.2; } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
static double getVal() { double checkVal; // assigning a value to the checkVal variable, // resulting from some calculations. if(checkVal <5) return 4.7; return 3.2; } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
static double getVal () { double checkVal; // assigning a value to the checkVal variable, // resulting from some calculations. if (checkVal <5) return 4.7; } |
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:
1 2 3 4 5 6 7 |
static <ReturnType> <FunctionName> {<ParameterType> <ParameterName>,. ... ... ) { return <returnValue>; } |
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:
1 2 3 4 5 6 7 |
static double product (double param1, double param2) { return param1* param2; } |
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.
Add the following code to Program.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Parameter { class Program { static int MaxValue(int[] intArray) { int maxVal = intArray[0]; for (int i = 1; i < intArray.Length; i++) { if(intArray[i] > maxVal) maxVal = intArray[i]; } return maxVal; } static void Main(string[] args) { int[] myArray = {1, 8, 3, 6, 2, 5, 9, 3, 0, 2}; int maxVal =MaxValue(myArray); Console.WriteLine("The maximum value in myArray is {0}",maxVal); Console.ReadKey(); } } } |
Run the program:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
static int MaxValue(int[] intArray) { int maxVal = intArray[0]; for (int i = 1; i < intArray.Length; i++) { if(intArray[i] > maxVal) maxVal = intArray[i]; } return maxVal; } |
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:
1 |
int myArray = {1 , 8, 3, 6, 2, 5, 9, 3, 0, 2}; |
When calling the C# function Maxvalue, the value is assigned to the Maxval variable of type int:
1 |
int maxVal = MaxValue(myArray); |
then we display this value on the screen using console.writeline()
1 |
Console.WriteLine ("The maximum value in myArray is {0} ", maxVal); |
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:
1 2 3 4 5 |
static void myFunction (string myString, double myDouble) { } |
cannot be called using the line:
1 |
myFunction (2.6, "Hello"); |
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:
1 |
myFunction("Hello"); |
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:
1 2 3 4 5 6 7 8 9 10 11 |
static void Main(string[] args) { doublet[] myArray = {1.3, 8.9, 3.3, 6.5, 2.7, 5.3}; double maxVal = MaxValue(myArray) ; Console.WriteLine(“The maximum value in myArray is {0}", maxVal) ; } |
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:
1 2 3 4 5 6 7 8 9 10 |
static <returnType> <functionName> (<n1Type> <n1Name>,, ..,params <type> [] <name>) { return <returnValue>; } |
In order to call this C# function, you need the following code:
1 |
<functionname> (<n1>,..., <value1>, <value2>,...); |
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:
1 |
string firstWord = getWord("This is a sentence.”); |
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:
1 |
string firstWord = getWord(“This is a sentence.”, 2) ; |
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:
1 |
string firstWord = getWord("This is a sentence. ", 4, 3); |
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.
Add the following code to Program.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ParameterArray { class Program { static int sumVals(params int[] vals) { int sum = 0; foreach (int val in vals) { sum += val; } return sum; } static void Main(string[] args) { int sum = sumVals(10, 53, 22, 94, 86); Console.WriteLine("summed Values ={0}", sum); Console.ReadKey(); } } } |
Run the program
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):
1 2 3 4 5 6 7 8 |
static int sumVals(params int[] vals) { } |
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:
1 |
int sum = sumVals (1, 5, 2, 9, 8); |
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
1 2 3 4 5 6 7 8 9 |
Static void showDouble(int val) { Val*=2; Console.WriteLine(“Val doubled ={0}”, val); } |
In this C# function, the passed parameter is doubled. If we call this function like this:
1 2 3 4 5 6 7 |
int myNumber = 5; Console.WriteLine(“myNumber = {0}”, myNumber); showDouble(myNumber) ; Console.WriteLine("myNumber = {0}”, myNumber); |
then the output on the console will look like this:
1 2 3 4 5 |
myNumber = 5 val doubled = 10 myNumber = 5 |
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:
1 2 3 4 5 6 7 |
int myNumber = 5; Console.WriteLine ("myNumber = {0}", myNumber); myNumber = showDouble (myNumber); Console.WriteLine (“myNumber = {0} “, myNumber); |
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:
1 2 3 4 5 6 7 8 9 |
static void showDouble (ref int val) { val * = 2; Console.WriteLine (“val doubled = {0} “, val); } |
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):
1 2 3 4 5 6 7 |
int myNumber = 5; Console.WriteLine ('myNumber = {0} *, myNumber); showDouble (ref myNumber); Console.WriteLine ('myNumber = {0} *, myNumber); |
In this case, the following text will be displayed on the console:
1 2 3 4 5 |
myNumber = 5 val doubled = 10 myNumber = 10 |
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:
1 2 3 4 5 6 7 |
const int myNumber = 5; Console.WriteLine ("mvNumber = {0} *, myNumber); showDouble (ref myNumber); Console.WriteLine ("myNumber = {0} “, myNumber); |
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:
1 2 3 4 5 |
int myNumber; showDouble (ref myNumber); Console.WriteLine (“myNumber = {0} “, myNumber); |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
static int MaxValue (int[] intArray, out int maxlndex) { int maxVal = intArray[0]; maxlndex = 0; for (int i = 1; i <int Array. Length; i ++) { if (intArray[i]> maxVal) { maxVal = intArray[i]; maxlndex = i; } } return maxVal; } |
This C# function can be used like this:
1 2 3 4 5 |
Int[] myArray = (1,8,3,6,7,8,4,3,9,0); Console.WriteLine(“The maximum value in myArrray is {0}”, maxValue(myArray, out maxIndex)); Console.WriteLine(“The first occurrence of this value is at element {0}, maxIndex+1); |
The result of its execution will be the following:
1 2 3 4 5 6 7 |
The maximum value in myArray is 9 (The maximum value contained in myArray is 9) The first occurrence of this value is at element 7 (The first occurrence with this value was found in item 7) |
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.
Add the following code in Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ScopeVariable { class Program { static void Write() { Console.WriteLine("myString = {0}", myString); } static void Main(string[] args) { string myString = "String defined in Main()"; Write(); } } } |
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:
1 2 3 4 |
Error1 The name 'myString' does not exist in the current context c:\users\shahzada fawad\documents\visual studio 2012\Projects\ScopeVariable\ScopeVariable\Program.cs ScopeVariable The variable'myString' is assigned but its value is never used |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ScopeVariable { class Program { static void Write() { string myString = "String defined in Write()"; Console.WriteLine("Now in Write()"); Console.WriteLine("myString = {0}", myString); } static void Main(string[] args) { string myString = "String defined in Main()"; Write(); Console.WriteLine("\nNow in Main()"); Console.WriteLine("myString = {0}", myString); Console.ReadKey(); } } } |
This code successfully passes the compilation procedure and produces the following result:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ScopeVariable { class Program { static string myString; static void Write() { string myString = "String defined in Write()"; Console.WriteLine("Now in Write()"); Console.WriteLine("Local myString = {0}", myString); Console.WriteLine("Global myString = {0}", Program.myString); } static void Main(string[] args) { string myString = "String defined in Main()"; Program.myString = "Global String"; Write(); Console.WriteLine("\nNow in Main()"); Console.WriteLine("Local myString = {0}", myString); Console.WriteLine("Global myString = {0}", Program.myString); Console.ReadKey(); } } } |
In this case, the following result will be displayed on screen:
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:
1 |
static string myString; |
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:
1 |
Program.myString = "Global string “; |
and is used in the write() function:
1 |
Console.WriteLine("Global myString = {0] “, Program.myString); |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ScopeVariable { class Program { static void showDouble(ref int val) { val *= 2; Console.WriteLine("val doubled = {0}", val); } static void Main(string[] args) { int val = 5; Console.WriteLine("val = {0}", val); showDouble(ref val); Console.WriteLine("val={0}", val); Console.ReadKey(); } } } |
The second program looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ScopeVariable { class Program { static int val; static void showDouble(ref int val) { val *= 2; Console.WriteLine("val doubled = {0}", val); } static void Main(string[] args) { int val = 5; Console.WriteLine("val = {0}", val); showDouble(ref val); Console.WriteLine("val={0}", val); Console.ReadKey(); } } } |
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.
Add the following code to Program.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MainFunction { class Program { static void Main(string[] args) { Console.WriteLine("{0} Command line Arguments were specified:", args.Length); foreach (string arg in args) Console.WriteLine(arg); Console.ReadKey(); } } } |
how to run command line arguments program:
Step1
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) .
Step2
Select the Configuration page Properties | Debugging and add to the Command Line installation Arguments (see picture below) those command line arguments, whatever you want.
step3
run the application:
Code Explanation:
The code used in this case, very simple:
1 2 3 4 5 |
Console.WriteLine (“{0} command line arguments were specified: ",args.Length); foreach (string arg in args) Console.WriteLine (arg); |
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),
and typing the following text and press enter button:
MainFunction 256 myFile.txt “a longer argument”