Search code examples
c#.netsingletonsymbolsresolve

C# Cannot resolve symbol


I don't know why I'm getting this error. Seems elementary. Anyway I have a singleton class called EmailSender. The code below is short and easy. The issue is that I can't use sender in the MainWindow class. Anything I try such as sender.Send() is treated as though I've done asdafsafas.Send(). It's treated as though it's a random string of characters. Don't know why this is happening.

using System;
using System.Net.Mail;
using System.Windows.Forms;

namespace SendMail
{
    public partial class MainWindow : Form
    {
        #region Private variables
        private MailMessage msg = new MailMessage();
        private EmailSender sender = EmailSender.GetInstance();
        #endregion

        public MainWindow()
        {
            InitializeComponent();

        }

        private MailMessage PrepareMailMessage()
        {

            return msg;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {

        }
    }
}

Here is the GetInstance method:

public static EmailSender GetInstance()
{
    return _instance ?? (_instance = new EmailSender());
}

Solution

  • This is because of the way you have this method defined (sender is a parameter). It's finding the method argument first, not your class level variable. You can qualify this:

    private void btnSend_Click(object sender, EventArgs e)
    {
        // sender here is the "(object sender, " paramater, so it's defined
        // as system object.
    
        // use this instead:
        this.sender.Send(); // The "this" will make the class find the instance level variable instead of using the "object sender" argument
    }