Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Return statement

Is there any way to break out of a function or exit from function that returns void?   
Answer: its simple use Return Statement.

The return statement terminates execution of the method in which it used and returns control to the calling method.  Return statement also return value for return type method, for void type method return statement can be omitted.

Examples:

Return with void type method:
In below example, if products not found in products generic list collection, return statement stop execution and pass control to calling method.
   public void InsertValidProducts()
         {
           
            //Get active list of latest products  
            var sActiveproducts = sorceDatabase.GetProducts();
           
            //Check if active products exist, if not exist send notification email
            if (sActiveproducts == null || sActiveproducts.Count == 0)
            {
                var warningNotificationMsg = string.Format(
                    "No active products found in the source database. " +
                    “Update for this dataset to be aborted. \n\n Machine name: {0}",
                    Environment.MachineName);
 
                //send error message notification and stop insert using return statement.
                consoleWriter.WriteWarningMessageToConsole(warningNotificationMsg);
                SendEmail(warningNotificationMsg, ErrorEmailSubject, ErrorEmailFrom);
                return;
            }
 
            //insert product into destination database
            foreach (var product in sActiveproducts)
            {
                destinationDatabase.InsertFavouriteGroup(product);
            }
        }
 


Return statement with return type method:

In below example, if products not found in products generic list collection, return statement return value false to calling method, else return true.
  public bool IsValidSourceProducts(List<Products> products)
        {
            //Check if active products exist ,if not exist send notification email
            if (products == null || products. Count == 0)
            {
                var warningNotificationMsg = string.Format(
                    "No active products found in the source database. " +
                    " Update for this dataset to be aborted. \n\n Machine name: {0}",
                    Environment.MachineName);
 
                //send error message notification and return value false 
                consoleWriter.WriteWarningMessageToConsole(warningNotificationMsg);
                SendEmail(warningNotificationMsg, ErrorEmailSubject, ErrorEmailFrom);
                return false;
            }
 
            //if found products in list return value true
            return true;
        }