I have a suspicion that the problem I am having has something to do with Visual Studio Code rather than with the C# code itself. I have recently configured my Visual Studio Code IDE to compile and build a C# (Command Line Console App) project and solution. But the moment I add meaningful code, it fales to properly recognize simple classes. Here is the simple test code I am trying:
using System;
using System.Net;
using System.Net.Mail;
using System.Net.WebSockets;
namespace SendEmailWIthGoogleSMTP
{
class Program
{
string fromMail ="[email protected]";
string password ="REDACTED";
MailMessage message = new MailMessage();
message.From = new MailAddress(fromMail);
message.Subject = "Test Subjecting";
message.To.Add(new MailAddress([email protected]);
message.Body ="This is a test";
message.IsBodyHtml= false;
}
}
But here is the problem. It complains that ‘message’ is not defined albeit it does not complain after I define it. I know that sounds confusing, so here is the screen shot.
3
Answers
Your code causes an issue because the initialization of MailMessage and its properties occurs directly within the class scope, which is not allowed. Instead, this should be done within a method, like Main() or another function.
Class-level statements in C# can only declare fields and methods.
Your code contains several issues that prevent it from even compiling
Main
methodThis compiles:
Your code looks like it has been written using top level statements but inside a class and should be:
It also looks like you’ve introduced a typo during redaction. The line below is missing double quotes around the email address and a closing parenthesis:
Should be: