Trim white space and return errors in c#

74 Views Asked by At

I'm moving from PHP (procedural) to C# and I've a number of errors in the following block - what am I doing wrong?

Objective is to pass in username and password values, then to trim, validate and return a list of errors (I'm using the dictionary to build an array of errors).

  1. "The name 'varUserName' does not exist in the current context".
  2. "else" = "Type or namespace definition, or end of file expected".

    public class Login (string InUserName, string InUserPass)
    {
        string varUserName;
        string varUserPass;
    
        // Dictionary object is c# equivalent of PHP's 'array["key"] = "value"'
        Dictionary<string, string> errMsg = new Dictionary<string, string>();
    
        varUserName = "123qwe";
    
        varUserName = varUserName.Trim();
    
        if ((varUserPass == "") && (varUserName == ""))
        {
            errMsg.Add("Username", "Username cannot be blank");
            errMsg.Add("Password", "Username cannot be blank");
        }
        else
        {
            if (varUserName == "")
            {
                errMsg.Add("Username", "Username cannot be blank");
            }
    
            if (varUserPass == "")
            {
                errMsg.Add("Password", "Password cannot be blank");
            }
        }
    }
    

Thanks Newbie Matt

1

There are 1 best solutions below

0
On

The problem is, that you do everything in your class. You can't do logic in your class. Put your code in a Method. Like so:

public class Login 
{
    string varUserName;
    string varUserPass;

    // Dictionary object is c# equivalent of PHP's 'array["key"] = "value"'
    Dictionary<string, string> errMsg = new Dictionary<string, string>();

    public Dictionary<string, string> LogMeIn()
    {
        varUserName = "123qwe";

        varUserName = varUserName.Trim();

        if ((varUserPass == "") && (varUserName == ""))
        {
            errMsg.Add("Username", "Username cannot be blank");
            errMsg.Add("Password", "Username cannot be blank");
        }
        else
        {
            if (varUserName == "")
            {
                errMsg.Add("Username", "Username cannot be blank");
            }

            if (varUserPass == "")
            {
                errMsg.Add("Password", "Password cannot be blank");
            }
        }
    return errMsg;
    }    

}

You can then call it like that in your code:

Login login = new Login();
var errMsg = login.LogMeIn();