In my console program, I want to send email to someone by using System.Net.Mail.MailMessage
. However, I cannot initialize it :(
namespace:
using System.Net;
using System.Net.Mail;
code:
class emailHelper
{
string to = "jane@address.com";
string from = "ben@address.com";
MailMessage message = new MailMessage(from, to);// errors here
}
the error message is about :
A field initializer cannot reference the non-static field, method, or property 'programA.emailHelper.from'
A field initializer cannot reference the non-static field, method, or property 'programA.emailHelper.to'
I have no idea that do I miss something to set before using MailMessage.
Any idea?
The error message give you all the information.
A field initializer cannot reference the non-static field, method, or property
So if you want to make it work, you should make your string fields static. Which I doubt is what you want.
class emailHelper
{
static string to = "jane@address.com";
static string from = "ben@address.com";
MailMessage message = new MailMessage(from, to);// errors here
}
Like I said this is not what you want from one helper method, to have static to and from address. Your code should look like this:
public class EmailHelper
{
public string To {get; set;}
public string From {get; set;}
public MailMessage message {get; set;}
public EmailHelper(string to, string from)
{
To = to;
From = from;
message = new MailMessage(from, to);
}
}
In this case you have addresses which are coming out of the helper and you can create multiple MailMessage
classes.
As the error message stated
A field initializer cannot reference the non-static field, method, or property
Which means you cant use a field to initialize another field. But you can make use of the constructor here, your class implementation will be like the following:
class emailHelper
{
string to = "jane@address.com";
string from = "ben@address.com";
MailMessage message; // Declare here
public emailHelper() // Constructor
{
message = new MailMessage(from, to);//initialize here
}
}
Or use a read only property getter like this:
public MailMessage Message
{
get { return new MailMessage(from, to); }
}
A field initializer cannot reference the nonstatic field, method, or property 'field' Instance fields cannot be used to initialize other instance fields outside a method. If you are trying to initialize a variable outside a method, consider performing the initialization inside the class constructor
Check the Documentation : Compiler Error CS0236
// CS0236.cs
public class MyClass
{
public int i = 5;
public int j = i; // CS0236
public int k; // initialize in constructor
MyClass()
{
k = i;
}
public static void Main()
{
}
}