.NET Framework Developer Center >
.NET Development Forums
>
Common Language Runtime
>
Determining Debug/Release mode
Determining Debug/Release mode
Hello,
Is it possible for the software to determine whether the code is being built in debug or release mode? I have several testing components I only want to allow in debug mode, to help ensure people aren't using it in their components for production?
Thanks.
Answers
- Lots of options, hope I got them all:
using System;
using System.Reflection;
using System.Diagnostics;
class Program {
static void Main(string[] args) {
// Compile time:
#if DEBUG
Console.WriteLine("In debug mode");
#else
Console.WriteLine("In release mode");
#endif
// Run-time:
Assembly asm = Assembly.GetExecutingAssembly();
DebuggableAttribute attr = (DebuggableAttribute)asm.GetCustomAttributes(typeof(DebuggableAttribute), false)[0];
if (attr.IsJITOptimizerDisabled) Console.WriteLine("In debug mode");
else Console.WriteLine("In release mode");
// Conditional method implementation:
SampleClass.ThisMethodIsOnlyCalledInDebugMode(1);
Console.ReadLine();
}
public static class SampleClass {
[Conditional("DEBUG")]
public static void ThisMethodIsOnlyCalledInDebugMode(int arg) {
Console.WriteLine("In debug mode");
}
}
}
The ConditionalAttribute is sweetest of all in my book, you don't even pay for building the argument list in Release mode, it is equivalent to not programming the method call at all. System.Diagnostics.Debug is implemented this way.
All Replies
- Lots of options, hope I got them all:
using System;
using System.Reflection;
using System.Diagnostics;
class Program {
static void Main(string[] args) {
// Compile time:
#if DEBUG
Console.WriteLine("In debug mode");
#else
Console.WriteLine("In release mode");
#endif
// Run-time:
Assembly asm = Assembly.GetExecutingAssembly();
DebuggableAttribute attr = (DebuggableAttribute)asm.GetCustomAttributes(typeof(DebuggableAttribute), false)[0];
if (attr.IsJITOptimizerDisabled) Console.WriteLine("In debug mode");
else Console.WriteLine("In release mode");
// Conditional method implementation:
SampleClass.ThisMethodIsOnlyCalledInDebugMode(1);
Console.ReadLine();
}
public static class SampleClass {
[Conditional("DEBUG")]
public static void ThisMethodIsOnlyCalledInDebugMode(int arg) {
Console.WriteLine("In debug mode");
}
}
}
The ConditionalAttribute is sweetest of all in my book, you don't even pay for building the argument list in Release mode, it is equivalent to not programming the method call at all. System.Diagnostics.Debug is implemented this way. Hmm... great!
Regards.


