Search code examples
c#asp.netrefout

Why I am not getting error with ref keyword


According to definition, ref keyword must be initialized before passing. while out parameters must be initialized before returning from the function.

Below is my snippet.

   public void TestRef(ref string n)
    {

    }

    public void TestOut(out string n)
    {

        n = "Hello"; //if I don't initialize, I gets compile time error. & That's right.

    }

Now while calling the methods.

string name;
TestOut(out name);//fine
TestRef(ref name) // why not throwing error.

In the above calls when trying to call TestRef() I have not initialized name parameter. But as per my understanding ref parameter must be initialized before passing.

It builds & run with no errors.


Solution

  • TestOut guarantees that name variable will be initialized when method will finish execution

    See out keyword

    Although variables passed as out arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns

    and ref

    An argument that is passed to a ref parameter must be initialized before it is passed. This differs from out parameters, whose arguments do not have to be explicitly initialized before they are passed. For more information, see out.

    Reorder the method calls and you will see the behavior you expect.