Search code examples
c#telnet

How to use variable of program class to another class?


I need to use the following string variable of program class to TelnetConnection class,I do all possible ways but not worked , please give me sugessions. Thank you.

program class

 class Program
 {      
    static void main()
    {
     string s = telnet.Login("some credentials");
    }
 }

TelnetConnection class

 class TelnetConnection
 {
      public string Login(string Username, string Password, int LoginTimeOutMs)
        {

            int oldTimeOutMs = TimeOutMs;
            TimeOutMs = LoginTimeOutMs;

            WriteLine(Username);

            s += Read();

            WriteLine(Password);

            s += Read();
            TimeOutMs = oldTimeOutMs;
            return s;
        }
  }

Solution

  • It should be something like this:

    public class TelnetConnection
    {
      public string Login(string Username, string Password, int LoginTimeOutMs)
      {
            string retVal = "";
    
            int oldTimeOutMs = TimeOutMs;
            TimeOutMs = LoginTimeOutMs;
    
            WriteLine(Username);
    
            retVal += Read();
    
            WriteLine(Password);
    
            retVal  += Read();
            TimeOutMs = oldTimeOutMs;
            return retVal ;
        }
     }
    

    In Program:

    class Program
    {      
        static void main()
        {
             var telnet = new TelnetConnection();
             string s = telnet.Login("some username", "some password", 123);
        }
     }
    

    But it seems there is some code missing in your example, especially the implementation of the Read method.

    If you want to alter the program's string variable, you can pass it to the method with the ref keyword:

    public class TelnetConnection
    {
      public string Login(string Username, 
                          string Password, int LoginTimeOutMs, ref string retVal)
      {
            //omitted
            retVal += Read();
    
            WriteLine(Password);
    
            retVal  += Read();
            TimeOutMs = oldTimeOutMs;
            return retVal ;
        }
     }
    

    In Program:

    class Program
    {      
        static void main()
        {
             var telnet = new TelnetConnection();
             string s = ""; 
             telnet.Login("some username", "some password", 123, ref s);
             //s is altered here
        }
     }