Only one return() for the entire method

Total Post:119

Points:835
C# 
C#
 1073  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. 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.

      Modified On Apr-03-2018 05:48:49 AM

Answer

NEWSLETTER

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