System ProgrammingLearn More About Functions in C# Programming

Learn More About Functions in C# Programming

Welcome back! In the previous article, we started discussing functions; a block of code that does one specific task. It can take one or more parameters, and it can return values. Let’s have a closer look at function parameters.

Parameter passing
To correctly pass parameters to a function, they must be of the same number, and type. For example, if a function takes two parameters: a string and an int, passing two strings or two integers will raise a compile-time error. Parameter types and numbers is often called a function signature. Take a note of this term as you will come across it a lot in this course, as well as in most texts that discuss programming.

But sometimes, you just don’t know the exact number of parameters you are going to pass to a given function. In this case C# offers you the parameter arrays.

Passing arbitrary number of parameters (parameter array)
You can pass any number of parameters to a function using this method. Just make sure that they are all of the same type, because a parameter array is, by definition, an array. Consider the following example:

class Program
    {
        static void myFunction(params string[] people)
        {
            foreach (string p in people){
                Console.WriteLine(p);
            }
        }

        static void Main(string[] args)
        {
            myFunction("Ahmed","Mohamed");
            Console.ReadLine();
        }
    }

Have a look at the function definition here. You are passing a special string array as a parameter, but you have preceded it with the keyword params. This way, you can pass any number of strings to the function when calling it. In the example, we have passed two strings, but more can be thrown.

Using parameter by reference and by value
Suppose that you have a greeting function that accepts a name (string), adds “Hello” to this name and prints the output. It could be something like this:

class Program
    {
        static string greet(string name)
        {
            name = "Hello " + name;
            return name;
        }

        static void Main(string[] args)
        {
            string name = "Mostafa";
            Console.WriteLine(greet(name));
            Console.ReadLine();
        }
    }

There is nothing new here, the function takes the name variable which contains the string “Mostafa”, adds another string, “Hello” to it, and returns the new string. But what about the “name” variable that we declared in the main function? The greet function changed this variable when it was passed to it, but did the original one change? Let’s make a small modification to the example to know the answer to this question:

question:
class Program
    {
        static string greet(string name)
        {
            name = "Hello " + name;
            return name;
        }

        static void Main(string[] args)
        {
            string name = "Mostafa";
            Console.WriteLine(greet(name));
            Console.WriteLine(name);
            Console.ReadLine();
        }
    }

If you run this code, you will have:

Hello Mostafa
Mostafa

The original variable stayed intact, holding the same value that we assigned to it. This is because function, by default, makes a local copy of the variable you pass to them as a parameter. All required processing is done on this copy, before the result is returned to the calling code.

But what if you want to change the original variable’s value? In other words, what if you want the name variable in the main function to hold “Hello Mostafa”? You have a couple of options: the first one is to assign the return value of the function to the name variable, like so:

static void Main(string[] args)
        {
            string name = "Mostafa";
            Console.WriteLine(greet(name));
            name = greet(name);
            Console.WriteLine(name);
            Console.ReadLine();
        }

Here you assigned the name variable twice, the first time when you initialized it, and the second time when you updated it after the function has returned, with the new value. The output of this code should be:

Hello Mostafa
Hello Mostafa

The second option, which will need less code and, thus, less error prone, it is to pass the parameter by reference. Have a look at this:

class Program
    {
        static string greet(ref string name)
        {
            name = "Hello " + name;
            return name;
        }

        static void Main(string[] args)
        {
            string name = "Mostafa";
            Console.WriteLine(greet(ref name));
            Console.WriteLine(name);
            Console.ReadLine();
        }
    }

You’ve probably observed two changes here:

  • The function definition has the keyword ref before defining the string parameter
  • When calling the function, the keyword ref is given before the variable itself.

If you run this code, you will have the same as the output of the previous example, when you manually changed the value of the variable.

Passing parameters by ref in C# has two constraints that must be considered:

  • The passed variable should not be a constant. Constants are a special type of variable in C#, which allows the value of the variable to stay unchanged throughout code execution. For example:
    const string name = "Ahmed";

    Obviously, this kind of variables is not a good candidate to be passed to a function, that will change it, by ref.

  • The passed variable should be initialized before passing it to the function by ref. So if we modified our example to be as follows, it won’t work:
class Program
    {
        static string greet(ref string name)
        {
            name = "Mostafa";
            name = "Hello " + name;
            return name;
        }

        static void Main(string[] args)
        {
            string name;
            Console.WriteLine(greet(ref name));
            Console.WriteLine(name);
            Console.ReadLine();
        }
     }

Learn Cloud Computing from Scratch for Beginners

Passing by reference, as an out parameter
Passing a constant to a function by ref does not make sense, as a constant should stay constant. But what about having to initialize the variable before passing it? What if you don’t have the value the variable will hold before calling the function? This is where the out parameter becomes handy. Have a look at our example it has been modified:

class Program
    {
        static void greet(out string name)
        {
            name = "Hello Mostafa";
        }

        static void Main(string[] args)
        {
            string name;
            greet(out name);
            Console.WriteLine(name);
            Console.ReadLine();
        }
    }

Now this is a lot different than the previous example. We omitted variable initialization, so the name does not contain any string before passing it to the function. Then we passed it to the greet function using the out keyword instead of ref. The function definition has been modified as well to accept the parameter by out, not by ref, and the function now is not returning any value, so it’s void. The result of running this code would be:

Hello Mostafa

What has been effectively done here is that you have a function that changes the value of one of your variables. This could be a good way to organize your code; by placing variable processing instructions in separate functions, and passing the variable by out.

It’s worth noting that any value assigned to a variable before passing the variable to the function is lost when passed as out. This makes sense because a function always initializes it’s out parameters. So if you write the code like this:

class Program
    {
        static void greet(out string name)
        {
            name = "Hello Mostafa";
        }

        static void Main(string[] args)
        {
            string name = "Ahmed";
            greet(out name);
            Console.WriteLine(name);
            Console.ReadLine();
        }
    }

It will return “Hello Mostafa” ignoring the original string you assigned to the name variable.

Conclusion
In this post, we had a closer look on different ways to pass parameters to a function. You saw how you can pass them by value, which is the default. Then you discovered how they can retain their values when passed by ref. Finally, you learned how you can pass even an uninitialized variable to a function, and have this function both initialize the variable and do whatever required to process it, by passing the variable as an out parameter.

In the coming article, we start discussing variable scopes and visibility, and we’ll also start examining the main function more thoroughly.

I hope you enjoyed reading this article, see you in the next one.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -