Is there any way to dynamically intercept method calls in a class in C#, equivalent to the Perl AUTOLOAD mechanism?
Case in point, I have a helper class with a 'core' method that writes to the system Event Log and a couple of convenience overloads to simplify the most common uses.
Now, I am seeing an emerging code pattern where I use try ... catch to attempt to write an entry, but ignore any failures that are related to the actual event log handling. For instance when trying to log an application exception when the event log is full, I want the application to crash with the "real" application exception, not the "event log" exception.
I have currently just created a new set of overloads that encapsulates this, but what I would really like to do is have dynamic handling of these methods, i.e. any method call to a method name starting with "Try" calls the respective "real" method, encapsulated in a try .. catch. This is would be so easy in Perl ;-) but can it even be done in C#?
Some code that might simplify the explanation:
public class SomeClass
{
// Core functionality
public static void WriteToLog(string message, EventLogEntryType type)
{
...
}
// Overloaded methods for common uses
public static void WriteToLog(SomeObject obj)
{
WriteToLog(obj.ToString(), EventLogEntryType.Information);
}
public static void WriteToLog(SomeException ex)
{
WriteToLog(ex.Message, EventLogEntryType.Error);
}
// Additional wrappers that ignores errors
// These are what I'd like to handle dynamically instead of manually:
public static void TryWriteToLog(SomeObject obj)
{
try
{
WriteToLog(obj);
}
catch (Exception logException)
{
Console.WriteLine(logException.Message);
}
}
public static void TryWriteToLog(SomeException ex)
{
try
{
WriteToLog(ex);
}
catch (Exception logException)
{
Console.WriteLine(logException.Message);
}
}
}