Execute code only while debugging with Visual Studio - c#

Is it possible to run specific code only when I am debugging the program via the debugging tools of Visual Studio?
If I use #if DEBUG or Conditional(“DEBUG”) the code is still triggered when running the .exe in the /Debug directory.

The #if DEBUG is for Conditional Compilation, it does not affect execution at runtime.
Instead use Debugger.IsAttached to branch at runtime.

Just to make it clear, the statements beginning with a hashtag are pre-processor directives. These directives are not present in the Translation Unit; thus these conditional statements do not exist in the compiled file.
EDIT It seems that this whole translation unit thing doesn't apply for C#

Related

#if DEBUG executes when external debugger attached? [duplicate]

This question already has answers here:
#if (DEBUG) VS System.Diagnostics.Debugger.IsAttached
(6 answers)
Closed 7 years ago.
Is #if DEBUG executed when the program is debugged after it has been released (for example by debugger tools like OllyDBG) or is it already nuked by the compiler on release build?
Means whatever I do with #if DEBUG is visible after the program has been created on release build?
#if DEBUG is processed during compilation. The code inside is not compiled if the DEBUG symbol is not defined, so it cannot be executed in a release build.
From MSDN:
When the C# compiler encounters an #if directive, followed eventually by an #endif directive, it will compile the code between the directives only if the specified symbol is defined.
To my understanding, compiler directives like #if DEBUG are resolved at compile time, depending on the set symbols. In practice this means that the build configuration is taken into consideration. If DEBUG is not set during build, attaching a debugger later cannot make the removed part of the implementation magically reappear; the corresponding parts are indeed 'nuked' during compilation.
It's a pre-processor directive, so the code within the #if is compiled only if DEBUG symbol exists.
Thus, you won't be able to debug a code that it's not part of compiled intermediate language code...
#if DEBUG has nothing to do with Debugging but simply includes or excludes a part of source code in a build/assembly.
The standard Release Build settings do not define DEBUG so any code inside a #if DEBUG will not be part of a Release Build

Compilation issue in C# .NET

I have the following code (inherited from a contractor):
public partial class StoredProcedures
{
#if NO_THREAD
readonly static String version = "XXXX, Version 1.02, Apr/29/2010";
#else
readonly static String version = "XXXX, Version 0.93, Dec/21/2006";
#endif
I can't seem to find NO_THREAD anywhere else. This is code that compiles and installs as a SQL assembly. Is it something special or am I missing something simple?
Try to check Project Properties->Build->General->Conditional compilation symbols for all Build configurations which you have for the project, It may be there.
Look for a #define statement. See the docs for #if preprocessor conditionals : http://msdn.microsoft.com/en-us/library/4y6tbswk.aspx
If you can't find a
define #NO_THREAD
Anywhere in the code, then it's probably because the contractor was defining the symbol by passing the /define compiler option.
See here for more details (typing from a cell, sorry for the format):
http://msdn.microsoft.com/en-us/library/0feaad6z.aspx
you should probably have a look at the c# pre-processor directives
No_Thread here is a symbol which can be defined by using #define No_Thread and when #define No_Thread is present then #if NO_THREAD will result in true and at compile time readonly static String version = "XXXX, Version 1.02, Apr/29/2010"; this statement will be compiled otherwise the next statement will be compiled.
this is generally used to differentiate between debug and release versions. have you noticed there are 2 versions in VS when you create a new project. if you write something like this somewhere in you code
#if DEBUG
Console.WriteLine("DEBUG VERSION");
#endif
then the string "DEBUG VERSION" would only be printed on the console when the project is in debug mode because the VS inserts a symbol DEBUG if you manually do it using the #define pre-processor then too this line would be compiled
NO_THREAD is a symbol for conditional compilation.
It can come from, #define NO_THREAD, from the project file, or from the nant file (or whatever method you use for building).
If it's defined, the first line of code is counted as part of the C# code. If it isn't, then the second is.
If that's the sole occurence, I'd say it was a hangover from something removed, but if you're uesd to using visual studio to build, then make sure there isn't a build file for nant in case the previous developer used that instead.
This is a conditional compilation symbol. In Visual Studio 2010, these appear on the Build page of your Project Properties in the Conditional compilation symbols text box. Probably one of your Configuration Manager configurations either contains this symbol or has at some point in the past. Presumably, there is another #if somewhere that disables a block of code that uses multiple threads if the NO_THREAD symbol is present.

How can I mark some lines of my code as it won't run in release?

I want to throw exceptions while debugging but in release mode I don't want to throw them. I am logging them into EventLog. This is the source of my problem but if I'm not wrong in C and Delphi there are some directives to make this.
In C# is there any way(directives or something else) which can ignore the lines in debug mode or release mode?
You can do it like this:
#if DEBUG
Console.WriteLine("Debug version");
#endif
http://msdn.microsoft.com/en-us/library/4y6tbswk.aspx
For your purposes (logging), you might also be interested in the ConditionalAttribute. It lets you mark an entire method as "remove all calls to this method in release builds".
If you do your logging in a lot of different places in your code, this would be much simpler than adding #if DEBUG around every single call site.
Use the #if DEBUG directive (and end with #endif). The DEBUG constant is defined when you run your application in debug mode (the Define DEBUG constant should be checked under the Build tab of your project properties).

Can I set a C# preprocessor directive from a central file?

I need to add some logging to my app, and it needs to be in release mode, and I need to make sure that the logging code isn't running in production. Therefore I'd like to use a #define and #if to make sure the log statements are removed when I move to production.
Trouble is, I need the logging in multiple files, and it's a pain to put a #define at the top of every file. Is there a way to have a centralized #define? That way I can remove the single #define rather than a #define from all files(which means I'll almost assuredly forget one).
On the command line, use the /define switch. In Visual Studio, choose the "Build" tab from the properties page for the project and fill in the "Conditional Compilation Symbols" section.
Consider also instead of using conditional compilation, to instead make your logging methods conditional methods. That's a more pleasant-looking alternative. That's how Debug.Assert works; it is a conditional method, so if the debug preprocessor symbol is not defined, the compiler simply removes all calls to the method before code generation.
See also my article on the subject:
http://ericlippert.com/2009/09/10/whats-the-difference-between-conditional-compilation-and-the-conditional-attribute/
Are you using Visual Studio? In the project Properties page, on the "Build" tab, there's a "Conditional compilation symbols" text box.
Yes, this is typically done in your build file, or the script you use which creates your build. You specify it as command-line arguments to MSBuild.
To add to Dave's answer, global conditional compilation symbols can also be specified in Visual.
Right-click on your project and go to Properties
Go to the Build tab
You can specify the symbols that you like (DEBUG is already turned on by default for Debug configurations, so this might actually give you what you want already) for the given configuration, or select "All Configurations" at the top to specify certain symbols for all configurations.
Call the logging everywhere you want.
Define the logging api entry methods with
[Conditional ("DEBUG")]
public void WriteDebugMessage(...)
Build your program in debug mode (which, by default, defines 'DEBUG' in VS). These calls will be part of your assembly.
Build your program in release mode (or - remove the DEBUG symbol from the build definition). These calls are now meaningless no-ops and won't run.
Seems like what you want?

How can I easily exclude certain lines of code from a compile?

Scattered throughout a software project I am working on are many lines of code that were written for debugging and utility purposes. Before I compile my code, I want a way to select whether or not these blocks of code should be included into my compile (something that won't require navigating the code commenting out). How can I do this?
I'm programming in c# and using Microsoft Visual Studio 2010.
Add the attribute [Conditional("DEBUG")] onto methods you only want to have execute in your debug build. See here for more detailed information.
I would suggest enclosing your blocks in #ifdef SOMETHING and #endif, and then defining SOMETHING in your project settings when you want to include that block in your compile.
You need preprocessor directives, or conditional compile statements. You can read about them here.
An example from that link:
#define TEST
using System;
public class MyClass
{
public static void Main()
{
#if (TEST)
Console.WriteLine("TEST is defined");
#else
Console.WriteLine("TEST is not defined");
#endif
}
}
The code is only compiled if TEST is defined at the top of the code. A lot of developers use #define DEBUG so they can enable debugging code and remove it again just by altering that one line at the top.
Consider using the Debug class to conditionally log, assert, etc. There are many advantages to this. You can choose to log (or not) at runtime. They limit you to (mostly) non-behavior-changing actions, addressing some of #STW's (valid) concern. They allow the use of third-party logging tools.
If they are for debugging, then the only acceptable solution is to surround such code with:
#ifdef DEBUG
#endif
This ensures that the code is included when you compile in debug mode but excluded in release mode.
You can use preprocessor directives w/ #if
You may want to consider moving these debugging functions out of the classes entirely--having your classes "change shape" between Debug and Release mode can be a real headache and can be difficult to diagnose problems.
You could consider creating a seperate "Debug" assembly which contains all your debugging helpers--then just make sure you can exclude it from the solution and build successfully without it.

Categories