.NET Framework Class Library Debug Class Updated: May 2011 Provides a set of methods and properties that help debug your code. This class cannot be inherited.

Inheritance Hierarchy
Namespace:
System.Diagnostics
Assembly:
System (in System.dll)

Syntax
Public NotInheritable Class Debug
public static class Debug
public ref class Debug abstract sealed
[<AbstractClass>]
[<Sealed>]
type Debug = class end
The Debug type exposes the following members.

Methods
|
| Name | Description |
|---|
.gif) .gif) .gif) .gif) | Assert(Boolean) | Checks for a condition; if the condition is false, displays a message box that shows the call stack. | .gif) .gif) .gif) .gif) | Assert(Boolean, String) | Checks for a condition; if the condition is false, outputs a specified message and displays a message box that shows the call stack. | .gif) .gif) .gif) .gif) | Assert(Boolean, String, String) | Checks for a condition; if the condition is false, outputs two specified messages and displays a message box that shows the call stack. | .gif) .gif) | Assert(Boolean, String, String, array<Object>[]()[]) | Checks for a condition; if the condition is false, outputs two messages (simple and formatted) and displays a message box that shows the call stack. | .gif) .gif) .gif) | Close | Flushes the output buffer and then calls the Close method on each of the Listeners. | .gif) .gif) .gif) | Fail(String) | Emits the specified error message. | .gif) .gif) .gif) | Fail(String, String) | Emits an error message and a detailed error message. | .gif) .gif) .gif) | Flush | Flushes the output buffer and causes buffered data to write to the Listeners collection. | .gif) .gif) | Indent | Increases the current IndentLevel by one. | .gif) .gif) | Print(String) | Writes a message followed by a line terminator to the trace listeners in the Listeners collection. | .gif) .gif) | Print(String, array<Object>[]()[]) | Writes a formatted string followed by a line terminator to the trace listeners in the Listeners collection. | .gif) .gif) | Unindent | Decreases the current IndentLevel by one. | .gif) .gif) .gif) | Write(Object) | Writes the value of the object's ToString method to the trace listeners in the Listeners collection. | .gif) .gif) .gif) | Write(String) | Writes a message to the trace listeners in the Listeners collection. | .gif) .gif) .gif) | Write(Object, String) | Writes a category name and the value of the object's ToString method to the trace listeners in the Listeners collection. | .gif) .gif) .gif) | Write(String, String) | Writes a category name and message to the trace listeners in the Listeners collection. | .gif) .gif) .gif) | WriteIf(Boolean, Object) | Writes the value of the object's ToString method to the trace listeners in the Listeners collection if a condition is true. | .gif) .gif) .gif) | WriteIf(Boolean, String) | Writes a message to the trace listeners in the Listeners collection if a condition is true. | .gif) .gif) .gif) | WriteIf(Boolean, Object, String) | Writes a category name and the value of the object's ToString method to the trace listeners in the Listeners collection if a condition is true. | .gif) .gif) .gif) | WriteIf(Boolean, String, String) | Writes a category name and message to the trace listeners in the Listeners collection if a condition is true. | .gif) .gif) .gif) .gif) | WriteLine(Object) | Writes the value of the object's ToString method to the trace listeners in the Listeners collection. | .gif) .gif) .gif) .gif) | WriteLine(String) | Writes a message followed by a line terminator to the trace listeners in the Listeners collection. | .gif) .gif) .gif) | WriteLine(Object, String) | Writes a category name and the value of the object's ToString method to the trace listeners in the Listeners collection. | .gif) .gif) | WriteLine(String, array<Object>[]()[]) | Writes a formatted message followed by a line terminator to the trace listeners in the Listeners collection. | .gif) .gif) .gif) | WriteLine(String, String) | Writes a category name and message to the trace listeners in the Listeners collection. | .gif) .gif) .gif) | WriteLineIf(Boolean, Object) | Writes the value of the object's ToString method to the trace listeners in the Listeners collection if a condition is true. | .gif) .gif) .gif) | WriteLineIf(Boolean, String) | Writes a message to the trace listeners in the Listeners collection if a condition is true. | .gif) .gif) .gif) | WriteLineIf(Boolean, Object, String) | Writes a category name and the value of the object's ToString method to the trace listeners in the Listeners collection if a condition is true. | .gif) .gif) .gif) | WriteLineIf(Boolean, String, String) | Writes a category name and message to the trace listeners in the Listeners collection if a condition is true. | Top

Remarks
If you use methods in the Debug class to print debugging information and check your logic with assertions, you can make your code more robust without affecting the performance and code size of your shipping product. This class provides methods to display an Assert dialog box, and to emit an assertion that will always fail. This class provides write methods in the following variations: Write, WriteLine, WriteIf, and WriteLineIf. The BooleanSwitch and TraceSwitch classes provide ways to dynamically control the tracing output. You can modify the values of these switches without recompiling your application. For information about using the configuration file to set a switch, see the Switch class and the Trace Switches topic. You can customize the tracing output's target by adding TraceListener instances to, or removing instances from, the Listeners collection. The Listeners collection is shared by both the Debug and the Trace classes; adding a trace listener to either class adds the listener to both. By default, the DefaultTraceListener class emits trace output. Note |
|---|
Adding a trace listener to the Listeners collection can cause an exception to be thrown while tracing, if a resource used by the trace listener is not available. The conditions and the exception thrown depend on the trace listener and cannot be enumerated in this topic. It may be useful to place calls to the Debug methods in try/catch blocks to detect and handle any exceptions from trace listeners. |
You can modify the level of indentation by using the Indent method or the IndentLevel property. To modify the indentation amount, use the IndentSize property. You can specify whether to automatically flush the output buffer after each write operation by setting the AutoFlush property to true. To set the AutoFlush and IndentSize for Debug, you can edit the configuration file corresponding to the name of your application. The configuration file should be formatted as shown in the following example.
<configuration>
<system.diagnostics>
<trace autoflush="true" indentsize="7" />
</system.diagnostics>
</configuration>
The ConditionalAttribute attribute is applied to the methods of Debug. Compilers that support ConditionalAttribute ignore calls to these methods unless "DEBUG" is defined as a conditional compilation symbol. Refer to a compiler's documentation to determine whether ConditionalAttribute is supported and the syntax for defining a conditional compilation symbol. Note |
|---|
In Visual Studio C# and Visual Basic projects, by default, the "DEBUG" conditional compilation symbol is defined for debug builds, and the "TRACE" symbol is defined for both debug and release builds. For information about how to disable this behavior, see the Visual Studio documentation. For information about conditional debugging in Visual C++, see The Debug Class in Visual C++. |
To define the "DEBUG" conditional compilation symbol in C#, add the /d:DEBUG option to the compiler command line when you compile your code using a command line, or add #define DEBUG to the top of your file. In Visual Basic, add the /d:DEBUG=True option to the compiler command line or add #Const DEBUG=True to the file.

Examples
The following example uses Debug to indicate the beginning and end of a program's execution. The example also uses the Indent and Unindent methods to distinguish the tracing output.
' Specify /d:DEBUG=True when compiling.
Imports System
Imports System.Data
Imports System.Diagnostics
Class Test
Shared Sub Main()
Debug.Listeners.Add(New TextWriterTraceListener(Console.Out))
Debug.AutoFlush = True
Debug.Indent()
Debug.WriteLine("Entering Main")
Console.WriteLine("Hello World.")
Debug.WriteLine("Exiting Main")
Debug.Unindent()
End Sub
End Class
// Specify /d:DEBUG when compiling.
using System;
using System.Data;
using System.Diagnostics;
class Test
{
static void Main()
{
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
Debug.AutoFlush = true;
Debug.Indent();
Debug.WriteLine("Entering Main");
Console.WriteLine("Hello World.");
Debug.WriteLine("Exiting Main");
Debug.Unindent();
}
}
// Specify /DDEBUG when compiling.
#using <System.dll>
using namespace System;
using namespace System::Diagnostics;
int main( void )
{
#if defined(DEBUG)
Debug::Listeners->Add( gcnew TextWriterTraceListener( Console::Out ) );
Debug::AutoFlush = true;
Debug::Indent();
Debug::WriteLine( "Entering Main" );
#endif
Console::WriteLine( "Hello World." );
#if defined(DEBUG)
Debug::WriteLine( "Exiting Main" );
Debug::Unindent();
#endif
return 0;
}

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileSupported in: 4, 3.5 SP1 Portable Class LibrarySupported in: Portable Class Library

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
This type is thread safe.

See Also

Change History
Date | History | Reason |
|---|
May 2011
| Updated the information about using the "DEBUG" conditional attribute. |
Customer feedback.
|
|
Biblioteca de clases de .NET Framework Debug (Clase) Proporciona un conjunto de métodos y propiedades que ayudan a depurar el código. Esta clase no puede heredarse.

Jerarquía de herencia
Espacio de nombres:
System.Diagnostics
Ensamblado:
System (en System.dll)

Sintaxis
Public NotInheritable Class Debug
public static class Debug
public ref class Debug abstract sealed
[<AbstractClass>]
[<Sealed>]
type Debug = class end
El tipo Debug expone los siguientes miembros.

Métodos
|
| Nombre | Descripción |
|---|
.gif) .gif) .gif) .gif) | Assert(Boolean) | Comprueba una condición; si esta es false, muestra un cuadro de mensaje con la pila de llamadas. | .gif) .gif) .gif) .gif) | Assert(Boolean, String) | Comprueba una condición; si esta es false, muestra un mensaje especificado y presenta un cuadro de mensaje con la pila de llamadas. | .gif) .gif) .gif) .gif) | Assert(Boolean, String, String) | Comprueba una condición; si esta es false, muestra dos mensajes especificados y presenta un cuadro de mensaje con la pila de llamadas. | .gif) .gif) | Assert(Boolean, String, String, array<Object>[]()[]) | Comprueba una condición; si esta es false, muestra dos mensajes (simple y con formato) y presenta un cuadro de mensaje con la pila de llamadas. | .gif) .gif) .gif) | Close | Vacía el búfer de resultados y llama al método Close en cada uno de los Listeners. | .gif) .gif) .gif) | Fail(String) | Emite el mensaje de error especificado. | .gif) .gif) .gif) | Fail(String, String) | Emite un mensaje de error y un mensaje de error detallado. | .gif) .gif) .gif) | Flush | Vacía el búfer de resultados y hace que los datos almacenados en el búfer se escriban en la colección de Listeners. | .gif) .gif) | Indent | Aumenta en uno el valor actual de la propiedad IndentLevel. | .gif) .gif) | Print(String) | Escribe un mensaje seguido de un terminador de línea en los agentes de escucha de seguimiento de la colección de Listeners. | .gif) .gif) | Print(String, array<Object>[]()[]) | Escribe una cadena con formato seguida de un terminador de línea en los agentes de escucha de seguimiento de la colección de Listeners. | .gif) .gif) | Unindent | Disminuye en uno el valor actual de la propiedad IndentLevel. | .gif) .gif) .gif) | Write(Object) | Escribe el valor del método ToString del objeto en los agentes de escucha de seguimiento de la colección de Listeners. | .gif) .gif) .gif) | Write(String) | Escribe un mensaje en los agentes de escucha de seguimiento de la colección de Listeners. | .gif) .gif) .gif) | Write(Object, String) | Escribe el nombre de categoría y el valor del método ToString del objeto en los agentes de escucha de seguimiento de la colección de Listeners. | .gif) .gif) .gif) | Write(String, String) | Escribe un nombre de categoría y un mensaje en los agentes de escucha de seguimiento de la colección de Listeners. | .gif) .gif) .gif) | WriteIf(Boolean, Object) | Escribe el valor del método ToString del objeto en los agentes de escucha de seguimiento de la colección de Listeners si una condición es true. | .gif) .gif) .gif) | WriteIf(Boolean, String) | Escribe un mensaje en los agentes de escucha de seguimiento de la colección de Listeners si una condición es true. | .gif) .gif) .gif) | WriteIf(Boolean, Object, String) | Escribe un nombre de categoría y el valor del método ToString del objeto en los agentes de escucha de seguimiento de la colección de Listeners si una condición es true. | .gif) .gif) .gif) | WriteIf(Boolean, String, String) | Escribe un nombre de categoría y un mensaje en los agentes de escucha de seguimiento de la colección de Listeners si una condición es true. | .gif) .gif) .gif) .gif) | WriteLine(Object) | Escribe el valor del método ToString del objeto en los agentes de escucha de seguimiento de la colección de Listeners. | .gif) .gif) .gif) .gif) | WriteLine(String) | Escribe un mensaje seguido de un terminador de línea en los agentes de escucha de seguimiento de la colección de Listeners. | .gif) .gif) .gif) | WriteLine(Object, String) | Escribe el nombre de categoría y el valor del método ToString del objeto en los agentes de escucha de seguimiento de la colección de Listeners. | .gif) .gif) | WriteLine(String, array<Object>[]()[]) | Escribe un mensaje con formato seguida de un terminador de línea en los agentes de escucha de seguimiento de la colección de Listeners. | .gif) .gif) .gif) | WriteLine(String, String) | Escribe un nombre de categoría y un mensaje en los agentes de escucha de seguimiento de la colección de Listeners. | .gif) .gif) .gif) | WriteLineIf(Boolean, Object) | Escribe el valor del método ToString del objeto en los agentes de escucha de seguimiento de la colección de Listeners si una condición es true. | .gif) .gif) .gif) | WriteLineIf(Boolean, String) | Escribe un mensaje en los agentes de escucha de seguimiento de la colección de Listeners si una condición es true. | .gif) .gif) .gif) | WriteLineIf(Boolean, Object, String) | Escribe un nombre de categoría y el valor del método ToString del objeto en los agentes de escucha de seguimiento de la colección de Listeners si una condición es true. | .gif) .gif) .gif) | WriteLineIf(Boolean, String, String) | Escribe un nombre de categoría y un mensaje en los agentes de escucha de seguimiento de la colección de Listeners si una condición es true. | Arriba

Comentarios
Si utiliza los métodos de la clase Debug para imprimir la información de depuración y comprobar la lógica con aserciones, puede hacer que el código sea más sólido sin que ello repercuta en el rendimiento y en el tamaño del código del producto de distribución. Esta clase proporciona métodos para mostrar un cuadro de diálogo Assert y emitir una aserción que siempre produzca un error. Esta clase proporciona métodos de escritura en las variaciones siguientes: Write, WriteLine, WriteIf y WriteLineIf. Las clases BooleanSwitch y TraceSwitch proporcionan medios para controlar de forma dinámica los resultados de la traza. Se pueden cambiar los valores de estos modificadores sin volver a compilar la aplicación. Para obtener información acerca de cómo utilizar el archivo de configuración para establecer un modificador, vea la clase Switch y el tema Modificadores de seguimiento. Para personalizar el destino de los resultados de la traza, agregue o quite instancias de TraceListener de la colección Listeners. La colección Listeners es compartida por las clases Debug y Trace; si agrega un agente de escucha de traza a cualquiera de las clases, éste se agrega a ambas. De forma predeterminada, la clase DefaultTraceListener emite resultados de seguimiento. Nota |
|---|
Al agregar un agente de escucha de seguimiento a la colección Listeners se puede originar una excepción que se producirá mientras tiene lugar la traza, si el recurso utilizado por el agente de escucha de traza no está disponible. Las condiciones y la excepción producidas dependen del agente de escucha de seguimiento y no se pueden enumerar en este tema. Puede ser útil para llamar a los métodos Debug en bloques try/catch para detectar y administrar cualquier excepción de los agentes de escucha de seguimiento. |
Se puede modificar el nivel de sangría con el método Indent o la propiedad IndentLevel. Para modificar la cantidad de aplicar sangría, utilice la propiedad IndentSize. Es posible especificar si hay que vaciar de forma automática el búfer de resultados después de cada operación de escritura; para ello, hay que establecer la propiedad AutoFlush en true. Con el fin de establecer las propiedades AutoFlush e IndentSize para Debug, se puede modificar el archivo de configuración que corresponde al nombre de la aplicación. El archivo de configuración debería tener el formato que se muestra en el siguiente ejemplo.
<configuration>
<system.diagnostics>
<trace autoflush="true" indentsize="7" />
</system.diagnostics>
</configuration>
El atributo ConditionalAttribute se aplica a los métodos de Debug. Los compiladores que admiten ConditionalAttribute omiten las llamadas a estos métodos a menos que se defina "DEBUG" como símbolo de compilación condicional. Consulte la documentación de un compilador para determinar si se admite ConditionalAttribute y la sintaxis para definir un símbolo de compilación condicional. Nota |
|---|
De forma predeterminada, en los proyectos de Visual Studio C# y Visual Basic se define el símbolo de compilación condicional "DEBUG" para las versiones de depuración y el símbolo "TRACE" para las versiones de depuración y de lanzamiento. Para obtener información sobre cómo deshabilitar este comportamiento, vea la documentación de Visual Studio. Para obtener información acerca de la depuración condicional en Visual C++, vea Debug (Clase) (C++/CLI). |
Para definir el símbolo de compilación condicional "DEBUG" en C# y J#, agregue la opción /d:DEBUG a la línea de comandos del compilador cuando compile su código mediante una línea de comandos, o bien agregue #define DEBUG a la parte superior del archivo. En Visual Basic, agregue la opción /d:DEBUG=True a la línea de comandos del compilador o agregue #Const DEBUG=True al archivo.

Ejemplos
En el siguiente ejemplo se utiliza Debug para indicar el comienzo y el fin de la ejecución de un programa. También se utilizan los métodos Indent y Unindent para distinguir los resultados de la traza.
' Specify /d:DEBUG=True when compiling.
Imports System
Imports System.Data
Imports System.Diagnostics
Class Test
Shared Sub Main()
Debug.Listeners.Add(New TextWriterTraceListener(Console.Out))
Debug.AutoFlush = True
Debug.Indent()
Debug.WriteLine("Entering Main")
Console.WriteLine("Hello World.")
Debug.WriteLine("Exiting Main")
Debug.Unindent()
End Sub
End Class
// Specify /d:DEBUG when compiling.
using System;
using System.Data;
using System.Diagnostics;
class Test
{
static void Main()
{
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
Debug.AutoFlush = true;
Debug.Indent();
Debug.WriteLine("Entering Main");
Console.WriteLine("Hello World.");
Debug.WriteLine("Exiting Main");
Debug.Unindent();
}
}
// Specify /DDEBUG when compiling.
#using <System.dll>
using namespace System;
using namespace System::Diagnostics;
int main( void )
{
#if defined(DEBUG)
Debug::Listeners->Add( gcnew TextWriterTraceListener( Console::Out ) );
Debug::AutoFlush = true;
Debug::Indent();
Debug::WriteLine( "Entering Main" );
#endif
Console::WriteLine( "Hello World." );
#if defined(DEBUG)
Debug::WriteLine( "Exiting Main" );
Debug::Unindent();
#endif
return 0;
}

Información de versión
.NET FrameworkCompatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileCompatible con: 4, 3.5 SP1 Compatible con:

Plataformas
Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2
.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Seguridad para subprocesos
Este tipo es seguro para la ejecución de subprocesos.

Vea también

Historial de cambios
Fecha | Historial | Motivo |
|---|
Mayo de 2011
| Actualizada la información sobre cómo utilizar el atributo condicional "DEBUG". |
Comentarios de los clientes.
|
|