Saturday, 22 December 2018

What is difference between ref and out keywords

What is difference between ref and out keywords?

ref and out modifier are useful whenever your method return more than one value. Both ref and out modifier are used to pass arguments within a method.

While using Ref, following points that you need to consider,

1. You must initialize the parameter first before you pass it as a reference.
2. It is two-way communication. ref parameters are used to get a value and potentially return a change to that value.

out parameters are very much like reference parameters. out means that the parameter has no value before going into the function. The called function must initialize it.

While using Out, following points that you need to consider,
1. You don't need to initialize the value in the calling function.
2. You must assign the value in the called function.

C# Program with ref and out keyword

public class CodeviewTest
    public static void Main() //calling method
        int salary = 200; //must be initialized       

        RefExample(ref salary);
        Console.WriteLine(salary); // salary=100

        int Sal; //optional

        OutExample(out Sal);
        Console.WriteLine(Sal); // Sal=300

        RefOutExample(ref salary, out Sal);
        Console.WriteLine(Sal); // Sal=400

    static void RefExample(ref int salary) //called method
        salary = 100;
    static void OutExample(out int salary) //called method
        salary = 300; //must be initialized
    //both ref and out keyword in a method
    static void RefOutExample(ref int salary, out int TotalSal) //called method
        TotalSal = salary+200; //must be initialized

/* Output

No comments:

Post a Comment

Note: only a member of this blog may post a comment.