Method Parameters Keywords in C# – ref, out, params with Examples

You can add keywords to method parameters in C#.

The three of them are: ref, out and params.

ref

The ref keyword can be used to pass arguments by reference. That means the parameter can be changed in the method and the changed value will be retained when control passes back to the calling method. Ref parameters need to be initialized before passing.

Example

 public class RefMethodParameterDemo
    {
        //The ref keyword causes arguments to be passed by reference.
        //The effect is that any changes made to the parameter in the method will
        //be reflected in that variable when control passes back to the calling method.

        public static void RefParamMethod1(ref int num1, ref int num2)
        {
            num1 = 20;
            num2 = 40;
        }

        static void Main()
        {
            //Need to be initialized before passing as argument
            int n1 = 0;
            int n2 = 0;

            //Both the method definition and the calling method
            //must explicitly use the ref keyword.
            RefParamMethod1(ref n1, ref n2);
            Console.WriteLine("n1 = " + n1);
            Console.WriteLine("n2 = " + n2);
            Console.Read();
        }
    }

o/p

n1 = 20
n2 = 40

out

The out keyword can be used to pass arguments by reference.

This is similar to the ref keyword, except that out doesn’t require the variable be initialized before being passed.

Example

class OutMethodParameterDemo
    {
        //A method with out parameter is useful when you want a method to return multiple values.
        //The method definition must explicitly use the out keyword
        //The method is required to assign a value before the method returns.
        public static void OutParamMethod1(out int num1, out string str1)
        {
            num1 = 20;
            str1 = "Hi I am out";
        }

        static void Main()
        {
            //No need to initialize the variable before passing
            int n1;
            string s1;
            //Both the method definition and the calling method must explicitly use the out keyword
            //The out keyword causes arguments to be passed by reference.
            OutMethodParameterDemo.OutParamMethod1(out n1, out s1);
            Console.WriteLine(n1);
            Console.WriteLine(s1);

            Console.Read();
        }
    }

o/p
20
Hi I am out

params

The params keyword lets you create a method parameter that takes an argument where the number of arguments is variable.

When you don’t know the exact number of arguments that will be passed in a method, then you can declare the method parameters using the params keyword.

Example

 public class ParamsParameterDemo
    {
        //The params keyword lets you specify a method parameter that
        //takes an argument where the number of arguments is variable.
        public void ParamsMethod1(params int[] numlist)
        {
            for (int i = 0; i < numlist.Length; i++)
                Console.WriteLine(numlist[i]);
            Console.WriteLine();
        }

        //In a method declaration, no additional parameters are permitted after the params keyword
        public void ParamsMethod2(params string[] strlist)
        {
            for (int i = 0; i < strlist.Length; i++)
                Console.WriteLine(strlist[i]);
            Console.WriteLine();
        }

        //Only one params keyword is permitted in a method declaration
        public void ParamsMethod3(params object[] objlist)
        {
            for (int i = 0; i < objlist.Length; i++)
                Console.WriteLine(objlist[i]);
            Console.WriteLine();
        }

        static void Main()
        {
            ParamsParameterDemo p1 = new ParamsParameterDemo();

            //Passing many integer values
            p1.ParamsMethod1(1, 7, 19, 25);

           //Passing Array as an argument
            int[] arr1 = { 5, 7, 9, 20, 16,22 };

            p1.ParamsMethod1(arr1);

            //Passing a string array
            string[] strarr1 = { "Mona", "Tony", "Jia" };
            p1.ParamsMethod2(strarr1);

            //Passing any datatype(objects)
            p1.ParamsMethod3(12, 'C', "Remo");

            Console.Read();
        }
    }

o/p
1
7
19
25

5
7
9
20
16
22

Mona
Tony
Jia

12
C
Remo

What are Bugs, Errors and Exceptions in Programming?

Bug

A bug is a mistake made by the programmer that should be fixed before the code is sent for production. A bug might cause an exception to be thrown. But the programmer should not rely on exceptions to handle the bugs. When found all the bugs should be fixed.

Error

An error is caused by the action of the user. For example, the user might enter a letter where a number is expected. An error can also result into an exception but that can be prevented by do doing proper validation. Whenever possible, errors should be anticipated and prevented.

Exception

In object-oriented programming, an exception is an object that encapsulates information about an unusual program occurrence.

Even after removing all bugs and anticipating all user errors, the program can still run into unpredictable problems like running out of memory or attempting to open a file that no longer exists. Such problems cause exceptions to be thrown by the program.

Thus you cannot prevent exceptions, but you can handle them so that they do not bring down your program.

Method Overshadowing in Java

Method Overshadowing is another name given to method overriding.

In Inheritance when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass.

 Here the method in the subclass is overshadowing the method in the superclass.

When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass.

If we want to explicitly call the method defined in the superclass then we can use the super keyword.

super.method_name  i.e the method we want to call of superclass.

Method Overriding in Java

  • When a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass.
  •  When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden.
  •  Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded.
Why Use Method Overriding?

Overridden methods allow Java to support run-time polymorphism.

Polymorphism is essential to object-oriented programming for one reason:

it allows a general class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods. Overridden methods are another way that Java implements the “one interface, multiple methods” aspect of polymorphism.