Thursday, March 18, 2010

Goto lablels in C#

This may be because I never needed it, but its good to know that C# also has "goto" statement label as we used to have way back in classic VB days. I was just browsing for some SharePoint stuff, and happened to see this code on MSDN web site.

private static int GetUniqueId(SPWeb web)
        {
            int returnValue = -1;
            int retryCounter = 0;
            int uniqueId = -1;

        ReTry:
            try
            {
                // Get the list and list item
                SPList list = web.Lists["Counter"];
                SPListItem item = list.Items[0];

                // Get the value for the unique id
                uniqueId = int.Parse(item["Title"].ToString());
                
                // Increment and update the value
                item["Title"] = uniqueId + 1;
                item.Update();
                
                // Set the value to return
                returnValue = uniqueId;
            }
            catch (Exception ex)
            {
                // Handle the exception by retrying 5 times
                retryCounter += 1;
                if (retryCounter <= 5)
                {
                    System.Threading.Thread.Sleep(2500);
                    goto ReTry;
                }
                else
                {
                    // Write the exception to the log
                }
            }
            return returnValue;
        }

No comments:

Post a Comment