Search code examples
c#sqlwin-universal-appwcfserviceclient

Cannot implicitly convert type 'System.Threading.Tasks.Task<String> to 'string'


I have a WCF Service with the method to return a string.

WCF Service :

public string selectName(int input)
    {
        string firstN, surN,result;
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT FirstName, Surname FROM tbUserAccounts WHERE StudentID = @ID", con);
        cmd.Parameters.Add("@ID", System.Data.SqlDbType.Int).Value = input;
        SqlDataReader reader = cmd.ExecuteReader();
        if (reader.Read())
        {
            firstN= reader["FirstName"].ToString();
            surN = reader["Surname"].ToString();
            result = firstN + " " + surN;
            con.Close();
            return result;

        }

        else
        {
            con.Close();
            return string.Empty;
        }

   }

This method works on the web service end. I've tried with WCFTest client and returns the values expected. Now on the application side I'm trying to use these values to add to my static class variables :

 private void btnSignIn_Click_1(object sender, RoutedEventArgs e)
    {

        Login._name = ServiceClientObj.selectNameAsync(int.Parse(studentIdBox.Text));
        Frame.Navigate(typeof(WelcomePage));


    }

the 'ServiceClientObj.selectNameAsync(int.Parse(studentIdBox.Text));' is underlined with an error saying

Cannot implicitly convert type 'System.Threading.Tasks.Task<String> to 'string'

I'm not familiar with WCF service so I don't understand fully about the use of async.

Any help or explanation would be appreciated. Thank you.


Solution

  • Try it like this:

    private async void btnSignIn_Click_1(object sender, RoutedEventArgs e)
    {
        Login._name = await ServiceClientObj.selectNameAsync(int.Parse(studentIdBox.Text));
        Frame.Navigate(typeof(WelcomePage));
    }
    

    Async method selectNameAsync returns Task<string> which is kind of a promise that it will return string in future, to wait this string result you can use keyword await, but to use it your method should have async keyword.

    Or you can use synchronous version of this method selectName if it's also generated by WCF, code will be like this:

    private void btnSignIn_Click_1(object sender, RoutedEventArgs e)
    {
        Login._name = ServiceClientObj.selectName(int.Parse(studentIdBox.Text));
        Frame.Navigate(typeof(WelcomePage));
    }