Out string C#

Hey guys!

I am using unity with an API for the first time and I’m a little stuck with a method:

static public bool User_Login(string emailAddress, string password, out string tokenID, out string errorMessage)

To use this to log in via unity I have tried:

if(GUI.Button (new Rect (25, 100, 150, 30), "Log in")){ 
	LH.User_Login(emailAddress, password, out tokenID, out errorMessage);
			print(tokenID + errorMessage);
	}

I am not too familiar with out strings however and how to use them. I’m assuming that it is a string that obtains a string from the server and returns it to me in unity somehow.

Here are my variables:

    private string emailAddress;
	private string password;
	private string tokenID;
	private string errorMessage;

I am testing it with my own login details and I get the error:

"problems connecting to NAME OF API SITE.

I think it is a problem with the out strings because when i use a method that does not contain out strings as its parameters I do not get an error at all.

I don’t think this have anything to do with the keyword out. Actually, the error is printed, as it’s supposed to.

First, that function is returning a bool, probably true if success. So you should do that :

if( LH.User_Login(...) ) 
    // Do something
else
    print(tokenID + errorMessage);

Then, try to find out why that function isn’t working. Most likely, one of the parameters is incorrect.

This is taking a few shortcuts for the sake of simplicity, but the most important difference is that an out parameter is passed by reference (most parameters are passed by value).

The difference is subtle, but very important:

  • Pass by value makes a copy of your variable; changes made to the copy have no effect on the original.
  • Pass by reference sends the memory address of your variable; the called function is not working with a copy, but with the original variable itself. Changes made to the variable persist.

This has some uses. For example, if you have a function like Unity’s Physics.Raycast(), which can tell you whether a raycast hit anything (returns a bool), while also populating a RaycastHit structure to tell you more about what, if anything, was actually hit.

It looks like your API call is using out parameters to return multiple values – notice that it can give you a tokenID and an errorMessage with just one call.

I hope this helps to explain what the out keyword does. Unfortunately, it doesn’t seem like that really explains your problem.

Perhaps the API is expecting some values that it’s not getting? For example, are you supposed to be passing in particular values on any or all of those parameters? If so, are you sure that you’re doing so?

Hopefully the API has some documentation that can help explain the error. Ideally they even mention the specific error message you’re getting, with possible troubleshooting steps.