`!' operator cannot be applied to operand of type `string'

Hi guys, got another couple of questions:

i am trying to do a very simple user login system against stored server player prefs database.
i know this is not the best but for now is all i need.

first how can i fix this compiler error:
The !' operator cannot be applied to operand of type string’

 if (!PlayerPrefs.GetString(Username) )
    [RPC]
    public void LoginIRequest(string Username, string Password)
    {
        if (!PlayerPrefs.GetString(Username) )
        {
            Debug.Log("Login request Username does not exist in player prefs");
            networkView.RPC("SendInvalidUserInfo",RPCMode.All,Username);
            return;
        }

second, will the return statement in bottom be enough or the right way to halt the process if no user found in player prefs?

thanks in advanced

You’re using the logical not ‘!’ operator on a method that returns a string, which is why you’re getting that error.

Depending on what PlayerPrefs.GetString returns if the key doesn’t exist, you can try one of the following approaches:

[If it returns null] Simply use PlayerPrefs.GetString(Username) == null

[If it returns a 0-length string] Simply use PlayerPrefs.GetString(Username).Length == 0

1 Like

Unity’s C# objects most/all convert to boolean (true if not null, false if null), which is why you can use the not ‘!’ operator on them. Most of the default C# library, including strings, don’t convert to boolean.

1 Like

thanks Stoven,

the second option worked for me.

much appreciated.

regards

Best to use string.IsEmptyOrNull() for this kind of check.

3 Likes