14
votes

Does C# support compiling filters? How do filters even work or what do they do?

Like reflector decompiles a filter as

try
{
}
catch(Exception e) when (?)
{
}
4
you may add a better definition or example of your wanted filter :)user57508

4 Answers

8
votes

C# did not support exception filters like VB does until C# 6. As for how they work, see Eric Lippert's "Finally" Does Not Mean "Immediately"

Starting in C# 6, exception filters are supported, as the C# FAQ demonstrates:

try { … } 
catch (MyException e) when (myfilter(e)) 
{ 
    … 
}

If the parenthesized expression after ‘if’ [now when] evaluates to true, the catch block is run, otherwise the exception keeps going.

Exception filters are preferable to catching and rethrowing because they leave the stack unharmed. If the exception later causes the stack to be dumped, you can see where it originally came from, rather than just the last place it was rethrown.

It is also a common and accepted form of “abuse” to use exception filters for side effects; e.g. logging. They can inspect an exception “flying by” without intercepting its course. In those cases, the filter will often be a call to a false-returning helper function which executes the side effects:

private static bool Log(Exception e) { /* log it */ ; return false; }
…
try { … }
catch (Exception e) when (Log(e)) {}

Thanks to Mafii for the link to the C# 6 documentation.

24
votes

Since C# 6 you can now do this.

try { … }
catch (MyException e) when (myfilter(e))
{
    …
}

This is different from using an if statement from within the catch block, using exception filters will not unwind the stack.

4
votes

Exception filters support in C# is introduced in C# 6 (Visual Studio "Dev14"):

try
{
    throw new ApplicationException("1");
}
catch (ApplicationException ex) when (ex.Message == "2")
{
    // this one won't execute.
}
catch (ApplicationException ex) when (ex.Message == "1")
{
    // this one will execute
}
0
votes

While catching exceptions, if you want to handle the exceptions differently then you can use Exception Filter
-- After C# 6.0
-- After VB 7.1 Using WHEN

1) C# Sample After C# 6.0

try
{
    throw new CustomException { Severity = 100 };
}
catch (CustomException ex) when (ex.Severity > 50)
{
    Console.WriteLine("*BING BING* WARNING *BING BING*");
}
catch (CustomException ex)
{
    Console.WriteLine("Whooops!");
}

Note : Keep in mind that the order matters

2) C# Sample Before C# 6.0

try
{
    throw new CustomException { Severity = 100 };
}
catch (CustomException ex)
{
   if (ex.Severity > 50)
    {
       Console.WriteLine("*BING BING* WARNING *BING BING*");
    }
   else
    {
       Console.WriteLine("Whooops!");
    }
}

Since this piece of code is equivalent to the previous one. means, they are equivalent, right? --- "But No they are not equivalent"
NOTE : exception filters don’t unwind the stack

Read it more from Here