How to return value from the method in C#

It might be a small question, but i am not understanding why it is throwing error.

Error:

Use of unassigned local variable status.

        public static bool HandleError(int eventId, int transactionId, DateTime timestamp, int userId, string message)
        {
            static bool status;
            ErrorMessage objHandleError = new ErrorMessage();
            try
            {
                objHandleError.EventId = eventId;
                objHandleError.TransactionId = transactionId;
                objHandleError.Timestamp = timestamp;
                objHandleError.UserId = userId;
                objHandleError.Message = message;
                if (string.IsNullOrEmpty(objHandleError.Message))
                {
                    status = false;
                }
                else
                    status = true;
                // Places the recived object on the service bus
                MessageBroadcastHelper.Send("ErrorMessage", objHandleError);

            }

            catch (Exception ex)
            {
                //To Do : if any exception we may write this exception to the event log.
                objHandleError.Exception = ex.ToString();
                //string ExceptionString = SerializeException(ex);            
            }

 return status;
        }

if i declare status variable in the class level,it is not throwing any exception, if i declare status variable outside the class i am not getting any errors.

Since i am using this variable only inside this method, i don't want to expose it out side, can any body point me what was the problem in the below code.

Jon Skeet
people
quotationmark

There are two problems here:

1) You've declared a local variable a static. That's invalid.

2) If an exception is thrown early in your method, you're catching it and then trying to return status without ever assigning a value to it.

I would suggest that in most cases you don't want to catch the exception at all - or if you do want to catch it (e.g. for logging), you should usually then use throw; to let it propagate up. If you really, really want to catch the exception and not rethrow it, you need to work out what value you want to be returned.

(I'd also suggest not catching bare Exception even if you do want to catch some exceptions. You should almost always catch a specific exception.)

To be honest, it's not clear how much use the returned value is anyway - the caller is passing in the message, so it's easy enough for them to check whether it's null or empty...

people

See more on this question at Stackoverflow