Home > Mobile >  How to get value from method C#
How to get value from method C#

Time:07-10

How to return a value from method. I am getting an error. Here is my code. I want to return top 5 email subjects by variable.

public static string ReadEmail(string username, string password, string domain)
    {

        string subject;

        ExchangeService exchange = new ExchangeService();
        Console.WriteLine("Registering Exchange connection");
        exchange.Credentials = new WebCredentials(username, password, domain);
        exchange.Url = new Uri("https://testmail/EWS/Exchange.asmx");

        Console.WriteLine("Reading mail");
        // Read top 5 mails
        FindItemsResults<Item> result = exchange.FindItems(WellKnownFolderName.Inbox, new ItemView(2));
        foreach (Item item in result)
        {
            EmailMessage message = EmailMessage.Bind(exchange, item.Id);
              subject = message.Subject.ToString();
            return subject;

        }    

    }

Here is the error

not all code paths return a value

CodePudding user response:

Sounds like you want to return 5 email subjects, so 5 strings. In which case you'd probably want to return an array of strings, string[] or List of strings List<string>.

The reason for your error is because if result is empty, the function will not return. The function needs to be able to return in all code paths.

CodePudding user response:

There are many problems in here. But if you want to get 5 items back you can do follow.

public static List<string> ReadEmail(string username, string password, string domain)
{

    List<string> subjects = new List<string>();

    ExchangeService exchange = new ExchangeService();
    Console.WriteLine("Registering Exchange connection");
    exchange.Credentials = new WebCredentials(username, password, domain);
    exchange.Url = new Uri("https://testmail/EWS/Exchange.asmx");

    Console.WriteLine("Reading mail");
    // Read top 5 mails
    FindItemsResults<Item> result = exchange.FindItems(WellKnownFolderName.Inbox, new ItemView(2));
    foreach (Item item in result)
    {
        EmailMessage message = EmailMessage.Bind(exchange, item.Id);
          subjects.Add(message.Subject.ToString());
    }  

    return subjects.Take(5).ToList();
}

Note that there is no sortorder, its not performant to iterate over all results to only get back 5. Also you should log if there are no results in your list and many things more.

  •  Tags:  
  • c#
  • Related