Search code examples
c#dictionarycookiesasync-awaithttpwebrequest

Return dictionary<String,String> + CookieContainer cookies from task


I have some code That Runs a Task to return a dictionary ... but sometimes i need it to return both the dictionary and a cookiecontainer with cookies ... here's the code

        static public async Task<Dictionary<String,String>> login(string server, string id, string pw)
    {


        CookieContainer cookies = new CookieContainer();
        HttpWebRequest newRequest = GetNewRequest(server, cookies);
        Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
        dictionary2.Add("name", id);
        dictionary2.Add("password", pw);
        dictionary2.Add("uni_url", server);
        Dictionary<string, string> parameters = dictionary2;
        HttpWebResponse response = await MakeRequest(newRequest, cookies, "login", server, parameters);
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            if (!reader.EndOfStream)
            {
                Dictionary<String, String> answer = new Dictionary<string, string>();
                answer.Add("HTML", reader.ReadToEnd());
                return answer;// here i need it to return CookieContainer .
            }
        }
        Dictionary<String, String> answerFailed = new Dictionary<string, string>();
        answerFailed.Add("LoginFailed", "LoginFailed! No Internet Connection!");
        return answerFailed;
    }

my question : How do I return two different things from the same method?


Solution

  • If you can change method you can use Tuple<T1,T2> To return two values from task:

     static public async Task<Tuple<Dictionary<String,String>,CookieContainer>> login(string server, string id, string pw)
        {
         CookieContainer cookies = new CookieContainer();
          Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
    // create result tuple
         var result = Touple.create(dictionary2,cookies);
         return result;
        }