Simplified, i have these 2 Extension
method:
public static class Extensions
{
public static string GetString(this Exception e)
{
return "Standard!!!";
}
public static string GetString(this TimeoutException e)
{
return "TimeOut!!!";
}
}
And here is where i use them:
try
{
throw new TimeoutException();
}
catch (Exception e)
{
Type t = e.GetType(); //At debugging this a TimeoutException
Console.WriteLine(e.GetString()); //Prints: Standard
}
I have more GetString()
extensions.
My try{...}catch{...}
is getting large and basically i search for ways to shorten it down to 1 catch that calls the extension based on the type of the exception.
Is there a way to call the right extension method at runtime?
To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.
Extension methods cannot be overridden the way classes and instance methods are. They are overridden by a slight trick in how the compiler selects which extension method to use by using "closeness" of the method to the caller via namespaces.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive. string s = "Hello Extension Methods"; int i = s. WordCount(); You invoke the extension method in your code with instance method syntax.
Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type." Essentially, an extension method is a special type of a static method and enable you to add functionality to an existing type even if you don't have access to the source code of the type.
As Yacoub Massad suggests you can use dynamic
, because with dynamic
method overload resolution is deferred at runtime through late binding.:
public static class Extensions
{
public static string GetString<T>(this T e) where T : Exception
{
// dynamic method overload resolution is deferred at runtime through late binding.
return GetStringCore((dynamic)e);
}
static string GetStringCore(Exception e)
{
return "Standard!!!";
}
static string GetStringCore(TimeoutException e)
{
return "TimeOut!!!";
}
static string GetStringCore(InvalidOperationException e)
{
return "Invalid!!!";
}
}
This should make the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With