This is related to the question about return type attributes and anonymous classes, but then for anonymous methods (or lambdas), but as far I could find this exact question does not seem to be on stackoverflow yet.
In code for business entities that we generate using CodeSmith we now have [DebuggerNonUserCode]
attributes, so they don't count in code coverage results. Unfortunately, the generated code uses anonymous methods that now still show up in code coverage with names like Class.<>c__DisplayClass3c
because of the way these are actually handled by the compiler.
Quick code example, with names and types changed to protect the innocent, so to speak:
public delegate T ReturnSomething<T>();
public static T SafeCall<T>(T whenNotSupported, ReturnSomething<T> method)
{
T result;
try
{
result = method();
}
catch (NotSupportedException)
{
result = whenNotSupported;
}
return result;
}
public static void CodeExample()
{
string foo = SafeCall<string>("OOPS!", delegate
{
//throw new NotSupportedException();
return "Ok";
});
}
Is there a way to get [DebuggerNonUserCode]
attributes on these methods so we could get rid of the name-mangled anonymous method names from our generated code from our code coverage results? Or do we need to rewrite that generated code to no longer use anonymous methods?
Putting the [DebuggerNonUserCode]
on the method
parameter of the SafeCall
method definition (before the ReturnSomething<T>
parameter type) does not compile and maybe would not do exactly what we would like if it would. The following also does not compile:
public static void CodeExample()
{
string foo = SafeCall<string>("OOPS!", [DebuggerNonUserCode] delegate
{
//throw new NotSupportedException();
return "Ok";
});
}
I've tried to have a quick look at the CSharp Language Specification, but have not had any luck finding a syntax that would allow applying attributes to anonymous methods (or lambdas). Did I miss it, or is this (currently?) impossible...?