ONLY ONE RETURN() FOR THE ENTIRE METHOD

Goti Bandu

Total Post:119

Points:835
Posted by  Goti Bandu
C# 
C#
 864  View(s)
Ratings:
Rate this:

I want a single return statement instead of having a return statement in each if statement. Can anybody tell me how to do it?

public object GetHeaderInfo(string agentId, string headerName)

 {

     if (headerName == "flyer")

     {

        var headerInfo = Service.GetFlierHeaderInfo(agentId);

        // headerinfo is of type Flier object

        return headerInfo;

     }

     if (headerName == "general")

     {

         var headerInfo = Service.GetHeaderInfo(agentId);

         // headerinfo is of type report object

         return headerInfo;

     }

     return 0;

 }

  1. ezra heywood

    Post:145

    Points:1019
    Re: Only one return() for the entire method

    Hi Goti,


    Declare it at the top of your method :

    public object GetHeaderInfo(string agentId, string headerName)

    {

        object headerInfo = 0;

        if (headerName == "flyer")

        {

            headerInfo = Service.GetFlierHeaderInfo(agentId);

        }

        if (headerName == "general")

        {

            headerInfo = Service.GetHeaderInfo(agentId);

        }

        return headerInfo;

    }

    The default value can be added during the initialization, it will be overwritten by any future assignation.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!