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

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.

Related

Preprocessor directive cannot be put in AND in C#

I need to put some code under a preprocessor directive.
such directives can be defined in different projects.
My situation is the following:
File Constants.cs (which is in project Proj1Dll.csproj)
#define DEV
... rest of the code
File Page1.cs (which is in project MainProj.csproj, which references Proj1Dll)
#define SHOW_BTN
...
#if (DEV && SHOW_BTN)
public static void Foo()
{
Debug.WriteLine("Both DEV and SHOW_BTN directives are defined");
}
#endif
Such configuration is not working, in the sense that method Foo() is not part of the compilation.
If I check instead #if (DEBUG && SHOW_BTN) everything is fine.
Is there a way to deal with such directives when they are defined in different projects?
Assuming you are using Visual Studio, you can go to the Project Properties, and under the Build tab, you will see 'Conditional compilation symbols'
Put your synbols in here and they will be recognised project wide.
In your example you would put just DEV if you wanted more than one, separate them with semicolon e.g. DEV;SHOW_BTN
If you want something to be solution wide and need only one symbol you can use the configuration manager to create a new configuration specifically for this build and call it what you like - this then gives you the same effect.
(It's why in your example DEBUG works)
Hope that helps.

how to install and use Code Contracts?

I have a basic question, might be it is so obvious but for some reason i can't seem to be successful with installing and using Code Contracts.
I've downloaded the package from MSDN, installed it following the online documentation but i still get an IDE warning for the below code statement:
Contract.Requires(inputParameter != "");
the IDE warning is:
"Method invocation is skipped. Compiler will not generate method invocation because the method is conditional, or it is partial method without implementation"
Anything I'm missing in the process of enabling Code Contracts? I'm using VS2010 Ultimate SP1
Most likely this is due to Code Contracts not being configured in the project settings. If you go to your project properties, you should see a Code Contracts tab. On the tab, select the mode you are building in (Debug|Release|Both) and then turn on Code Contracts features by checking the appropriate check boxes.
I've seen the warning that you detail when Code Contracts are not set to Build.
If you don't see the Code Contracts tab, then you might need to install Code Contracts on your machine. Do this by downloading and installing the installer from here.
Conditional compilation is all driven from compiler preprocessor definitions. This is the same approach used for the DEBUG constant, although Visual Studio hides the definition of that behind a checkbox. It's an efficient approach because when those symbols aren't defined then the methods aren't called at all; importantly the parameters being passed aren't evaluated either, so you can use relatively expensive checks in your code contracts without worrying about those checks slowing down release builds.
Microsoft's introduction to Code Contracts says this:
Most methods in the contract class are conditionally compiled; that is, the compiler emits calls to these methods only when you define a special symbol, CONTRACTS_FULL, by using the #define directive. CONTRACTS_FULL lets you write contracts in your code without using #ifdef directives; you can produce different builds, some with contracts, and some without.
Although this talks about using #define in the code to turn on code contracts:
#define CONTRACTS_FULL
as #NirMH said in the comments it's usually better to define it in the conditional compilation symbols for the project so you can have it on for some builds and off for others.
Note that CONTRACTS_FULL is the only option you have, although it's clearly been named to allow the possibility of more granular control in future.

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).

Removing code from Release build in .NET

I've been doing some performance testing around the use of System.Diagnostics.Debug, and it seems that all code related to the static class Debug gets completely removed when the Release configuration is built. I was wondering how the compiler knows that. Maybe there is some class or configuration attribute that allows to specify exactly that behavior.
I am trying to create some debugging code that I want completely removed from the Release configuration, and I was wondering if I could do it just like the Debug class where simply changing the configuration parameters removes the code.
You can apply the ConditionalAttribute attribute, with the string "DEBUG" to any method and calls to that item will only be present in DEBUG builds.
This differs from using the #ifdef approach as this allows you to release methods for use by other people in their DEBUG configurations (like the Debug class methods in the .NET framework).
Visual Studio defines a DEBUG constant for the Debug configuration and you can use this to wrap the code that you don't want executing in your Release build:
#ifdef DEBUG
// Your code
#endif
However, you can also decorate a method with a Conditional attribute, meaning that the method will never be called for non-Debug builds (the method and any call-sites will be removed from the assembly):
[Conditional("DEBUG")]
private void MyDebugMethod()
{
// Your code
}
Have a look at preprocessor directives...
#if DEBUG
//code
#endif

Categories