-3

While writing the following code i am getting "not all code paths return a value" error for GetLayerByName() function.

 private ILayer GetLayerByName(string slayerName)
        {

            IMxDocument doc = m_application.Document as IMxDocument;
            IMap pMap = doc.FocusMap;

            for (int i = 0; i < pMap.LayerCount; i++)
            {
                ILayer player = pMap.get_Layer(i);

                if (player.Name == slayerName)
                {
                    return player;
                }
            }
        }
  • 2
    Obviously there is no return value outside the if..there should be at least a return null – elasticrash Oct 10 '15 at 13:02
  • What if no layer's name matches slayerName? That is the condition you are not accounting for in this code. – Devdatta Tengshe Oct 10 '15 at 13:03
4

As with what @elasticrash said... a function in .NET needs to have a return value given all scenarios that come through it. So, you should adjust your code in a manner like:

private ILayer GetLayerByName(string slayerName) {

        IMxDocument doc = m_application.Document as IMxDocument;
        IMap pMap = doc.FocusMap;

        for (int i = 0; i < pMap.LayerCount; i++)
        {
            ILayer player = pMap.get_Layer(i);

            if (player.Name == slayerName)
            {
                return player;
            }
        }
        //if you made it this far, there isn't a slayerName that matches the player.Name property
        //so to make .NET happy you need to assign another return value
        //typically I return null and verify in the code that 
        //calls this function that the return value isn't null
        return null;
    }

So in the method that calls GetLayerByName(), make sure the function actually returned something.

ILayer layer = GetLayerByName("name");
if(layer == null){
//handle the case here
}
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.