Edited this question with another related question. Please help me: Can I use the same variable names for several methods of a class?

advertisements

Thanks everyone for your answers. The one issue I am having though is when I print the value of each of the variables in the methods Helpdesk and IT, it does not print "help", "hellp123", and "Welcome Helpdesk!" rather prints "admin", "admin" and "Welcome". THe case is same for the method IT.

public class Login
{
    public string[] array = new string[3];
    public string UserName;
    public string Password;
    public string Message;
}

public Login
{
   UserName = array[0] = "admin";
   Password = array[1] = "admin";
   Message = array[2] = "Welcome";

}

public void Helpdesk
{
    UserName = "help";
    Password = "help123";
    Message = "Welcome Helpdesk!";
    Console.WriteLine(UserName); //still prints admin
    Console.WriteLine(Password); // still prints admin
    Console.WriteLine(Message); // still prints Welcome
}
public void IT
{
    UserName = "it";
    Password = "Pa$$w0rd";
    Message = "Welcome IT!";

}


Can I use the same variable names: UserName, Password and Message for methods: Helpdesk and IT for the same class Login like below?
public class Login { public string[] array = new string[3]; public string UserName; public string Password; public string Message; }

public Login
{
   UserName = array[0] = "admin";
   Password = array[1] = "admin";
   Message = array[2] = "Welcome";
}

public void Helpdesk
{
    UserName = "help";
    Password = "help123";
    Message = "Welcome Helpdesk!";
}
public void IT
{
    UserName = "it";
    Password = "Pa$$w0rd";
    Message = "Welcome IT!";

}


The variables you talk of are fields in the class. The are confined to that class. If you create new variables with the same name, but not inside the same class (like you do above), that is allowed. If you do it inside your class, it will shadow the field, which is considered a bad practice.

Note: if you only assign to the field from inside the class (like you may imply in your question, but the code is not complete), you simply change its value.

public class Login
{
    public string Message;
    public string Name;

    public void Test()
    {
       Message =  "Welcome";  // changes field, same as this.Message = ...
       var Name = "Me";       // does not change field, hides field Name
    }

}