athosbr99
athosbr99

Reputation: 483

How to use get and set?

I have 4 elements:

I wanted to use get and set to define the message and the person who is going to recieve the email.

I've done this:

 class EmailGT
{
    private string _mensagem = string.Empty;
    private string _destinatario = string.Empty;

    public string mensagem
    {
        get { return _mensagem; }
        set { _mensagem = value; }
    }

    public string destinatario
    {
        get { return _destinatario; }
        set { _destinatario = value; }
    }

}
}

In the Email.cs I have this (I didn't post the whole code since it wouldn't be necessary):

 class Email
{
    public void SendEmail()
    {
        EmailGT x = new EmailGT();
        string destinatario = x.destinatario;
        string mensagem = x.mensagem;
        System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
        message.To.Add(destinatario);
        message.Subject = "something";
        message.Body = mensagem;

And in the Windows Forms (both) I have this:

  EmailGT x = new EmailGT();
  Email z = new Email();
  x.mensagem = "teste 2";
  x.destinatario = "my email";
  z.SendEmail();

However, both fields go empty on the Email.cs. I guess I didn't really understand how to use this. Can somebody say what is wrong? Thanks!

Upvotes: 0

Views: 125

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

You should change SendEmail method declaration to take EmailGT instance as a parameter, and use that instance within the method, instead of creating local variable.

public void SendEmail(EmailGT x)
{
    string destinatario = x.destinatario;
    string mensagem = x.mensagem;
    System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
    message.To.Add(destinatario);
    message.Subject = "something";
    message.Body = mensagem;
}

And usage:

EmailGT x = new EmailGT();
x.mensagem = "teste 2";
x.destinatario = "my email";

Email z = new Email();
z.SendEmail(x);

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 360016

The EmailGT x in SendEmail has nothing to do with the EmailGT x on which you're setting properties. Perhaps you want to change SendEmail to accept an EmailGT as a parameter:

class Email
{
    public void SendEmail(EmailGT x)
    {
        string destinatario = x.destinatario;
        string mensagem = x.mensagem;
        System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
        message.To.Add(destinatario);
        message.Subject = "something";
        message.Body = mensagem;
        // snip
    }
}

then you'd pass the EmailGT to SendEmail:

EmailGT x = new EmailGT();
x.mensagem = "teste 2";
x.destinatario = "my email";

Email z = new Email();
z.SendEmail(x);

Upvotes: 2

Related Questions