-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;
                }
            }
        }

closed as off-topic by Vince, Fezter, John Powell, BradHards, Evil Genius Oct 27 '15 at 10:51

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions relating to general Information Technology, with no clear GIS component, are off-topic here, but can be researched/asked at Stack Overflow (software development), Super User (computing hardware and software) and Database Administrators (relational databases)" – Vince, Fezter, John Powell, BradHards, Evil Genius
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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
}

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