I need to implement a HtmlHelper extension in my MVC project simply just to output some string but ONLY in the DEBUG mode, not in RELEASE.
My first attempt would be:
[Conditional("DEBUG")]
public static string TestStringForDebugOnly(this HtmlHelper helper, string testString)
{
return testString;
}
But obviously that would give a compile error:
“The Conditional attribute is not valid because its return type is not void.”
So my understanding is once you set the [Conditional] attribute, it doesn’t allow anything to be returned? Why?
Is there another way to implement this kind of function? Any help would be much appreciated.
You can use a preprocessor directive:
As far as your original question as to why, a peek at section 17.4.2 of the C# specification indicates:
I can only speculate as to why the designers of the language decided this, but I would venture to guess it’s because the C# compiler does not compile the method call into IL if the condition is
false, so in effect it’s as if you never called the method (which would cause some obvious problems at run-time if a return value was expected!)