Can the region be used as a variable?

54 views Asked by At

I'm performing a cleanup of the database in my code. It looks as follows:

#region Orders and SubOrders
try
{
    ... // this code tries to remove the Orders and the SubOrders
}
catch (Exception ex)
{
    _logger.Error($"An exception occurred while cleaning Orders and SubOrders. Error message=[{ex.Message}]");
}

#region Customers
try
{
    ... // this code tries to remove the Customers
}
catch (Exception ex)
{
    _logger.Error($"An exception occurred while cleaning Customers. Error message=[{ex.Message}]");
}

Is it possible to replace the _logger line by something like:

_logger.Error($"An exception occurred while cleaning [{#currentregion}]. Error message=[{ex.Message}]");

Thanks in advance

2

There are 2 answers

0
Marc Wittmann On

No you can't. In C#, the #region directive is a feature of the C# preprocessor that allows you to group sections of code for organizational purposes in the editor, but it doesn't have any runtime presence. Once your code is compiled, the #region directives are not preserved in the compiled binary

5
Matthew Watson On

You cannot do this using #region.

Possibly a better design would be to have a separate method for each of your current #region sections. Then you could use nameof to get at the name of the method to inject into the exception message:

void RemoveOrdersAndSubOrders()
{
    try
    {
        ... // this code tries to remove the Orders and the SubOrders
    }
    catch (Exception ex)
    {
        _logger.Error($"An exception occurred in {nameof(RemoveOrdersAndSubOrders)}. Error message=[{ex.Message}]");
    }
}

(Of course, if you were also logging the stack trace when the exception was thrown, you would already have the name of the method.)

Arguably it's a better design to split up a long method into smaller method calls anyway.


In response to your supplementary question:

If you have access to the Logger class you could change your Error() method to something like this:

public static void Error(
    string message,
    [CallerFilePath]   string file   = "",
    [CallerMemberName] string method = "",
    [CallerLineNumber] int    line   = 0)
{
    Console.WriteLine($"Error \"{message}\" in method \"{method}\" on line {line} of file \"{file}\"");
}

(Obviously you would change the Console.WriteLine() to whatever you're using to output the logging data.)

When you call this, you only supply the message parameter - the other parameters will be populated automatically.

That way when you log your errors, it will output the method name and the file path and line number.

If you don't have access to the implementation of Error() you could write your own ExtendedError() wrapper for it (possibly making it an extension method so you could call _logger.ExtendedError("some error message");)