Search code examples
c#entity-frameworkintvoid

Cannot implicitly convert type 'void' to 'int'?


Oke so I am fairly new to programming and I don't get why I get this error.

My method should store mails which it does in this method:

    public void StoreMail(PhishingMail PhishingMail)
    {
        using (var phishingMailStorage = new PhishFinderModel())
        {
            phishingMailStorage.PhishingMail.Attach(PhishingMail);

            phishingMailStorage.SaveChanges();

        }

And then in my processPhishingMail method it calls the Store method. But then I get the error: Cannot implicitly convert type 'void' to 'int'.

public void ProcessPhishingMail(PhishingMail phishingMail)
{                     
      Hashtable phishingUrls;
      int phishingMailId;
      int phishingUrlId;
      //Error convertion
      phishingMailId = _storageAgent.StoreMail(phishingMail);

So I can't really find a solution to convert from void to int. Maybe it's not possible?

My question is: how do I convert these types in my code?

Please don't be harsh I am really new to this. It feels like I am swimming in an ocean of information and I don't know where to look or start. So any suggested tutorials are very welcome.


Solution

  • The method

    public void StoreMail(PhishingMail PhishingMail)

    is not returning any value. So when you do:

    phishingMailId = _storageAgent.StoreMail(phishingMail);

    You are getting that error, since StoreMail is declared as void, which means it does not return anything.

    To fix this, simply call StoreMail like this:

    _storageAgent.StoreMail(phishingMail);

    If you intend to return a value from StoreMail, then you must change it to return an int value:

    public int StoreMail(PhishingMail PhishingMail)
    {
        using (var phishingMailStorage = new PhishFinderModel())
        {
            phishingMailStorage.PhishingMail.Attach(PhishingMail);
    
            phishingMailStorage.SaveChanges();
        }
    
        return someIdWhichYouNeedToFigureOut;
    }