Home > database >  C# - Expecting "{" in if statement but got "("
C# - Expecting "{" in if statement but got "("

Time:11-27

I'm writing a program for school that emails the user once a certain device detects the moisture level is above a certain value. I don't know C/C#/C (I have to write it in C# since the main program is in C#), I do know python however so using the main program combined with my Python knowledge I was able to make an if statement. The issue is, when ran it gives the error expected "{" but got "(". Since this isn't an issue in Python I don't really know what I'm doing wrong. Any help? NOTE: Emails, passwords, and names have been removed for my security.

/// Adding time (In progress. Lines 2, 3, 12, 26)

// Send email if plant is too moist
if (MoistureValue > 2) {
{
    var smtpClient = new SmtpClient("smtp.gmail.com")
{
    Port = 587,
    Credentials = new NetworkCredential("[email protected]", "RandomPasswordRandomNumber"),
    EnableSsl = true,
   
};

smtpClient.Send("[email protected]", "My name", "Plant Moisture", "Your plant is above its reccomended moisture go check on it!.");
}
}
// Send email if plant is too dry
if (MoistureValue < 2) { 
{
    var smtpClient = new SmtpClient("smtp.gmail.com")
{
    Port = 587,
    Credentials = new NetworkCredential("[email protected]", "RandomPasswordRandomNumber"),
    EnableSsl = true,
    
};
    
smtpClient.Send("[email protected]", "My Name", "Plant Moisture", "Your plant is a little dry, go water it!");
}
}

CodePudding user response:

In programming we strive to reduce repetition. Your code can be reduced to:

if (MoistureValue != 2) {

    var smtpClient = new SmtpClient("smtp.gmail.com", 587) {
        Credentials = new NetworkCredential("[email protected]", "RandomPasswordRandomNumber"),
        EnableSsl = true,
    };

    var msg = MoistureValue > 2 ? 
      "Your plant is above its recommended moisture go check on it!." : 
      "Your plant is a little dry, go water it!";
    
    smtpClient.Send("[email protected]", "My Name", "Plant Moisture", msg);
    
}

CodePudding user response:

Your braces are imbalanced. And you should get the case in which nothing will happen out of the way first. So maybe you go with.

// When everything is okay, do nothing.
if (MoistureValue == 2) return;

var smtpClient = new SmtpClient("smtp.gmail.com")
    {
        Port = 587,
        Credentials = new NetworkCredential("[email protected]", "RandomPasswordRandomNumber"),
        EnableSsl = true,
    };

var message = MoistureValue < 2 ? "Your plant is a little dry, go water it!" : "Your plant is above its reccomended moisture go check on it!.";

smtpClient.Send("[email protected]", "My name", "Plant Moisture", message);

  • Related