locked
Is it ok to use a discard here? RRS feed

  • Question

  • User-374939276 posted

    Hi. I want to know if I can replace the var response = with the discard _ = . Thank you!

    var response = await client.SendEmailAsync(msg);
    // Replace with:
    _ = await client.SendEmailAsync(msg);

    static async Task Execute()
    {
    var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
    var client = new SendGridClient(apiKey);
    var from = new EmailAddress("test@example.com", "Example User");
    var subject = "Sending with SendGrid is Fun";
    var to = new EmailAddress("test@example.com", "Example User");
    var plainTextContent = "and easy to do anywhere, even with C#";
    var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
    var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
    var response = await client.SendEmailAsync(msg);
    }
    Thursday, January 2, 2020 6:26 AM

Answers

  • User-821857111 posted

    You can use a discard there, or you can just simply call await client.SendEmailAsync(msg); without assigning the return value to anything.

    Both approaches are "correct" (will compile) but I believe the discard was introduced to cater for instances where you can't ignore the return, such as out parameters where you don't want to use the result. I wouldn't use it in your example. Nor would I assign the return value to var response unless I intended to use it.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 2, 2020 9:28 AM

All replies

  • User-821857111 posted

    You can use a discard there, or you can just simply call await client.SendEmailAsync(msg); without assigning the return value to anything.

    Both approaches are "correct" (will compile) but I believe the discard was introduced to cater for instances where you can't ignore the return, such as out parameters where you don't want to use the result. I wouldn't use it in your example. Nor would I assign the return value to var response unless I intended to use it.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 2, 2020 9:28 AM
  • User-374939276 posted

    Thank you!

    Thursday, January 2, 2020 10:02 AM