+ Start a Discussion
Sohail Barat 14Sohail Barat 14 

Non-void method might not return a value or might have statement after a return statement.

I am getting this error in my code:
Non-void method might not return a value or might have statement after a return statement.
My code is as under:
public class ContactSearch {
    public static list<contact> searchForContacts(String Surname,String PCode)
    {    
        list<Contact> ListIDandName = [select ID, name, phone from contact];
        for(Contact search: ListIDandName)
        {
            if(search.name==surname && search.MailingPostalCode==PCode)
            {
                return ListIDandName;
            }
        }
    }
}
Best Answer chosen by Sohail Barat 14
John PipkinJohn Pipkin
Your return statement is inside an IF statement. If you have a non-void method, it has to return something regardless of condition. For example, if the condition you wrote is not met, you can return null. like:
 
public class ContactSearch {
    public static list<contact> searchForContacts(String Surname,String PCode)
    {    
        list<Contact> ListIDandName = [select ID, name, phone from contact];
        for(Contact search: ListIDandName)
        {
            if(search.name==surname && search.MailingPostalCode==PCode)
            {
                return ListIDandName;
            }
            else
            	return null;
        }
    }
}

 

All Answers

John PipkinJohn Pipkin
Your return statement is inside an IF statement. If you have a non-void method, it has to return something regardless of condition. For example, if the condition you wrote is not met, you can return null. like:
 
public class ContactSearch {
    public static list<contact> searchForContacts(String Surname,String PCode)
    {    
        list<Contact> ListIDandName = [select ID, name, phone from contact];
        for(Contact search: ListIDandName)
        {
            if(search.name==surname && search.MailingPostalCode==PCode)
            {
                return ListIDandName;
            }
            else
            	return null;
        }
    }
}

 
This was selected as the best answer
Sohail Barat 14Sohail Barat 14
Thank You :)