-1

What does it mean when the function look like this?

 bool Connect([ref string  errormessage])
 {
     \\Code
 }

Do I call it like this?

 string error = "";
 if(!<MyInstance>.Connect(error))
       MessageBox.Show(error);
Bigboss
  • 355
  • 1
  • 3
  • 17

1 Answers1

1

Assuming the function call is as below, since the above has a syntax error.

bool Connect(ref string errormessage)
{
    \\Code
}

Then, this means that

The argument errormessage is being passed as reference, not value.

When an argument is passed as reference:

  1. The argument must be initialized before it is passed.
  2. Both the method definition and the calling method must explicitly use the ref keyword.
  3. Any change to the parameter in the called method (i.e., errormessage) is reflected on the argument (i.e., error) in calling method.

string error = ""; //Point 1  
if(!<MyInstance>.Connect(ref error)) //Point 2 


bool Connect(ref string errormessage) //Point 2
{
    errormessage = "Error Occurred"; 
    // At this moment the value of error becomes 'Error Occurred' since 
    // it was passed by reference - Point 3
}

Regarding the syntax error, [ref string errormessage] will give a syntax error, since it's not a valid attribute i.e., [Optional] string errormessage.

Additionally, using the optional attribute with a ref is not of much use, as an argument passed with ref cannot have a default value.

Source: MSDN.

ZerosAndOnes
  • 1,083
  • 1
  • 13
  • 25
  • 1
    Nit: In point 3, you mean "Any change to the parameter". I would have just edited it in, but I wasn't sure it would be appropriate. (The argument appears in the calling code; within the method it's just the parameter. So `ref error` is an argument, and `errormessage` is a parameter.) – Jon Skeet Apr 21 '18 at 06:42
  • Thanks, it would surely have been appropriate. – ZerosAndOnes Apr 21 '18 at 06:55