# Boolean Estructura

## Definición

Representa un valor booleano (`true` o `false`).Represents a Boolean (`true` or `false`) value.

``public value class Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>``
``public value class Boolean : IComparable, IConvertible``
``public value class Boolean : IComparable, IComparable<bool>, IEquatable<bool>``
``public struct Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>``
``````[System.Serializable]
public struct Boolean : IComparable, IConvertible``````
``````[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>``````
``public struct Boolean : IComparable, IComparable<bool>, IEquatable<bool>``
``````type bool = struct
interface IConvertible``````
``````[<System.Serializable>]
type bool = struct
interface IConvertible``````
``````[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type bool = struct
interface IConvertible``````
``type bool = struct``
``````Public Structure Boolean
Implements IComparable, IComparable(Of Boolean), IConvertible, IEquatable(Of Boolean)``````
``````Public Structure Boolean
Implements IComparable, IConvertible``````
``````Public Structure Boolean
Implements IComparable, IComparable(Of Boolean), IEquatable(Of Boolean)``````
Herencia
Boolean
Atributos
Implementaciones

## Comentarios

Una Boolean instancia de puede tener uno de dos valores: `true` o `false` .A Boolean instance can have either of two values: `true` or `false`.

La Boolean estructura proporciona métodos que admiten las siguientes tareas:The Boolean structure provides methods that support the following tasks:

En las siguientes secciones se explican estas tareas y otros detalles de uso:The following sections explain these tasks and other usage details:

### Dar formato a valores booleanosFormat Boolean values

La representación de cadena de un Boolean es "true" para un `true` valor o "false" para un `false` valor.The string representation of a Boolean is either "True" for a `true` value or "False" for a `false` value. La representación de cadena de un Boolean valor se define mediante los campos de solo lectura TrueString y FalseString .The string representation of a Boolean value is defined by the read-only TrueString and FalseString fields.

El método se usa ToString para convertir valores booleanos en cadenas.You use the ToString method to convert Boolean values to strings. La estructura booleana incluye dos ToString sobrecargas: el método sin parámetros ToString() y el ToString(IFormatProvider) método, que incluye un parámetro que controla el formato.The Boolean structure includes two ToString overloads: the parameterless ToString() method and the ToString(IFormatProvider) method, which includes a parameter that controls formatting. Sin embargo, dado que este parámetro se omite, las dos sobrecargas producen cadenas idénticas.However, because this parameter is ignored, the two overloads produce identical strings. El ToString(IFormatProvider) método no admite el formato dependiente de la referencia cultural.The ToString(IFormatProvider) method does not support culture-sensitive formatting.

En el ejemplo siguiente se muestra el formato con el ToString método.The following example illustrates formatting with the ToString method. Tenga en cuenta que en el ejemplo se usa la característica de formato compuesto , por lo que ToString se llama implícitamente al método.Note that the example uses the composite formatting feature, so the ToString method is called implicitly.

``````using System;

public class Example
{
public static void Main()
{
bool raining = false;
bool busLate = true;

Console.WriteLine("It is raining: {0}", raining);
Console.WriteLine("The bus is late: {0}", busLate);
}
}
// The example displays the following output:
//       It is raining: False
//       The bus is late: True
``````
``````Module Example
Public Sub Main()
Dim raining As Boolean = False
Dim busLate As Boolean = True

Console.WriteLine("It is raining: {0}", raining)
Console.WriteLine("The bus is late: {0}", busLate)
End Sub
End Module
' The example displays the following output:
'       It is raining: False
'       The bus is late: True
``````

Dado que la Boolean estructura solo puede tener dos valores, es fácil agregar formato personalizado.Because the Boolean structure can have only two values, it is easy to add custom formatting. Para un formato personalizado simple en el que otros literales de cadena se sustituyen por "true" y "false", puede usar cualquier característica de evaluación condicional compatible con el lenguaje, como el operador condicional en C# o el operador if en Visual Basic.For simple custom formatting in which other string literals are substituted for "True" and "False", you can use any conditional evaluation feature supported by your language, such as the conditional operator in C# or the If operator in Visual Basic. En el ejemplo siguiente se usa esta técnica para dar formato a Boolean los valores como "Yes" y "no" en lugar de "true" y "false".The following example uses this technique to format Boolean values as "Yes" and "No" rather than "True" and "False".

``````using System;

public class Example
{
public static void Main()
{
bool raining = false;
bool busLate = true;

Console.WriteLine("It is raining: {0}",
raining ? "Yes" : "No");
Console.WriteLine("The bus is late: {0}",
busLate ? "Yes" : "No" );
}
}
// The example displays the following output:
//       It is raining: No
//       The bus is late: Yes
``````
``````Module Example
Public Sub Main()
Dim raining As Boolean = False
Dim busLate As Boolean = True

Console.WriteLine("It is raining: {0}",
If(raining, "Yes", "No"))
Console.WriteLine("The bus is late: {0}",
If(busLate, "Yes", "No"))
End Sub
End Module
' The example displays the following output:
'       It is raining: No
'       The bus is late: Yes
``````

En el caso de operaciones de formato personalizadas más complejas, incluido el formato dependiente de la referencia cultural, puede llamar al String.Format(IFormatProvider, String, Object[]) método y proporcionar una ICustomFormatter implementación.For more complex custom formatting operations, including culture-sensitive formatting, you can call the String.Format(IFormatProvider, String, Object[]) method and provide an ICustomFormatter implementation. En el ejemplo siguiente se implementan las ICustomFormatter IFormatProvider interfaces y para proporcionar cadenas booleanas que tengan en cuenta la referencia cultural para las referencias culturales de inglés (Estados Unidos), francés (Francia) y ruso (Rusia).The following example implements the ICustomFormatter and IFormatProvider interfaces to provide culture-sensitive Boolean strings for the English (United States), French (France), and Russian (Russia) cultures.

``````using System;
using System.Globalization;

public class Example
{
public static void Main()
{
String[] cultureNames = { "", "en-US", "fr-FR", "ru-RU" };
foreach (var cultureName in cultureNames) {
bool value = true;
CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName);
BooleanFormatter formatter = new BooleanFormatter(culture);

String result = String.Format(formatter, "Value for '{0}': {1}", culture.Name, value);
Console.WriteLine(result);
}
}
}

public class BooleanFormatter : ICustomFormatter, IFormatProvider
{
private CultureInfo culture;

public BooleanFormatter() : this(CultureInfo.CurrentCulture)
{ }

public BooleanFormatter(CultureInfo culture)
{
this.culture = culture;
}

public Object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}

public String Format(String fmt, Object arg, IFormatProvider formatProvider)
{
// Exit if another format provider is used.
if (! formatProvider.Equals(this)) return null;

// Exit if the type to be formatted is not a Boolean
if (! (arg is Boolean)) return null;

bool value = (bool) arg;
switch (culture.Name) {
case "en-US":
return value.ToString();
case "fr-FR":
if (value)
return "vrai";
else
return "faux";
case "ru-RU":
if (value)
return "верно";
else
return "неверно";
default:
return value.ToString();
}
}
}
// The example displays the following output:
//       Value for '': True
//       Value for 'en-US': True
//       Value for 'fr-FR': vrai
//       Value for 'ru-RU': верно
``````
``````Imports System.Globalization

Module Example
Public Sub Main()
Dim cultureNames() As String = { "", "en-US", "fr-FR", "ru-RU" }
For Each cultureName In cultureNames
Dim value As Boolean = True
Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture(cultureName)
Dim formatter As New BooleanFormatter(culture)

Dim result As String = String.Format(formatter, "Value for '{0}': {1}", culture.Name, value)
Console.WriteLine(result)
Next
End Sub
End Module

Public Class BooleanFormatter
Implements ICustomFormatter, IFormatProvider

Private culture As CultureInfo

Public Sub New()
Me.New(CultureInfo.CurrentCulture)
End Sub

Public Sub New(culture As CultureInfo)
Me.culture = culture
End Sub

Public Function GetFormat(formatType As Type) As Object _
Implements IFormatProvider.GetFormat
If formatType Is GetType(ICustomFormatter) Then
Return Me
Else
Return Nothing
End If
End Function

Public Function Format(fmt As String, arg As Object,
formatProvider As IFormatProvider) As String _
Implements ICustomFormatter.Format
' Exit if another format provider is used.
If Not formatProvider.Equals(Me) Then Return Nothing

' Exit if the type to be formatted is not a Boolean
If Not TypeOf arg Is Boolean Then Return Nothing

Dim value As Boolean = CBool(arg)
Select culture.Name
Case "en-US"
Return value.ToString()
Case "fr-FR"
If value Then
Return "vrai"
Else
Return "faux"
End If
Case "ru-RU"
If value Then
Return "верно"
Else
Return "неверно"
End If
Case Else
Return value.ToString()
End Select
End Function
End Class
' The example displays the following output:
'          Value for '': True
'          Value for 'en-US': True
'          Value for 'fr-FR': vrai
'          Value for 'ru-RU': верно
``````

Opcionalmente, puede usar archivos de recursos para definir cadenas booleanas específicas de la referencia cultural.Optionally, you can use resource files to define culture-specific Boolean strings.

### Convertir a y desde valores booleanosConvert to and from Boolean values

La Boolean estructura implementa la IConvertible interfaz.The Boolean structure implements the IConvertible interface. Como resultado, puede usar la Convert clase para realizar conversiones entre un Boolean valor y cualquier otro tipo primitivo en .net, o puede llamar a las Boolean implementaciones explícitas de la estructura.As a result, you can use the Convert class to perform conversions between a Boolean value and any other primitive type in .NET, or you can call the Boolean structure's explicit implementations. Sin embargo, Boolean no se admiten las conversiones entre y los siguientes tipos, por lo que los métodos de conversión correspondientes producen una InvalidCastException excepción:However, conversions between a Boolean and the following types are not supported, so the corresponding conversion methods throw an InvalidCastException exception:

Todas las conversiones de números enteros o de punto flotante a valores booleanos convierten valores distintos de cero en `true` y cero valores en `false` .All conversions from integral or floating-point numbers to Boolean values convert non-zero values to `true` and zero values to `false`. En el ejemplo siguiente se muestra cómo llamar a las sobrecargas seleccionadas de la Convert.ToBoolean clase.The following example illustrates this by calling selected overloads of the Convert.ToBoolean class.

``````using System;

public class Example
{
public static void Main()
{
Byte byteValue = 12;
Console.WriteLine(Convert.ToBoolean(byteValue));
Byte byteValue2 = 0;
Console.WriteLine(Convert.ToBoolean(byteValue2));
int intValue = -16345;
Console.WriteLine(Convert.ToBoolean(intValue));
long longValue = 945;
Console.WriteLine(Convert.ToBoolean(longValue));
SByte sbyteValue = -12;
Console.WriteLine(Convert.ToBoolean(sbyteValue));
double dblValue = 0;
Console.WriteLine(Convert.ToBoolean(dblValue));
float sngValue = .0001f;
Console.WriteLine(Convert.ToBoolean(sngValue));
}
}
// The example displays the following output:
//       True
//       False
//       True
//       True
//       True
//       False
//       True
``````
``````Module Example
Public Sub Main()
Dim byteValue As Byte = 12
Console.WriteLine(Convert.ToBoolean(byteValue))
Dim byteValue2 As Byte = 0
Console.WriteLine(Convert.ToBoolean(byteValue2))
Dim intValue As Integer = -16345
Console.WriteLine(Convert.ToBoolean(intValue))
Dim longValue As Long = 945
Console.WriteLine(Convert.ToBoolean(longValue))
Dim sbyteValue As SByte = -12
Console.WriteLine(Convert.ToBoolean(sbyteValue))
Dim dblValue As Double = 0
Console.WriteLine(Convert.ToBoolean(dblValue))
Dim sngValue As Single = .0001
Console.WriteLine(Convert.ToBoolean(sngValue))
End Sub
End Module
' The example displays the following output:
'       True
'       False
'       True
'       True
'       True
'       False
'       True
``````

Al convertir de booleano a valores numéricos, los métodos de conversión de la Convert clase se convierten `true` en 1 y `false` en 0.When converting from Boolean to numeric values, the conversion methods of the Convert class convert `true` to 1 and `false` to 0. Sin embargo, Visual Basic funciones de conversión convierten `true` a 255 (para conversiones a Byte valores) o-1 (para todas las demás Conversiones numéricas).However, Visual Basic conversion functions convert `true` to either 255 (for conversions to Byte values) or -1 (for all other numeric conversions). En el ejemplo siguiente se convierten `true` valores numéricos mediante Convert un método y, en el caso del ejemplo Visual Basic, mediante el operador de conversión propio del lenguaje Visual Basic.The following example converts `true` to numeric values by using a Convert method, and, in the case of the Visual Basic example, by using the Visual Basic language's own conversion operator.

``````using System;

public class Example
{
public static void Main()
{
bool flag = true;

byte byteValue;
byteValue = Convert.ToByte(flag);
Console.WriteLine("{0} -> {1}", flag, byteValue);

sbyte sbyteValue;
sbyteValue = Convert.ToSByte(flag);
Console.WriteLine("{0} -> {1}", flag, sbyteValue);

double dblValue;
dblValue = Convert.ToDouble(flag);
Console.WriteLine("{0} -> {1}", flag, dblValue);

int intValue;
intValue = Convert.ToInt32(flag);
Console.WriteLine("{0} -> {1}", flag, intValue);
}
}
// The example displays the following output:
//       True -> 1
//       True -> 1
//       True -> 1
//       True -> 1
``````
``````Module Example
Public Sub Main()
Dim flag As Boolean = true

Dim byteValue As Byte
byteValue = Convert.ToByte(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, byteValue,
byteValue.GetType().Name)
byteValue = CByte(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, byteValue,
byteValue.GetType().Name)

Dim sbyteValue As SByte
sbyteValue = Convert.ToSByte(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, sbyteValue,
sbyteValue.GetType().Name)
sbyteValue = CSByte(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, sbyteValue,
sbyteValue.GetType().Name)

Dim dblValue As Double
dblValue = Convert.ToDouble(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, dblValue,
dblValue.GetType().Name)
dblValue = CDbl(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, dblValue,
dblValue.GetType().Name)

Dim intValue As Integer
intValue = Convert.ToInt32(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, intValue,
intValue.GetType().Name)
intValue = CInt(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, intValue,
intValue.GetType().Name)
End Sub
End Module
' The example displays the following output:
'       True -> 1 (Byte)
'       True -> 255 (Byte)
'       True -> 1 (SByte)
'       True -> -1 (SByte)
'       True -> 1 (Double)
'       True -> -1 (Double)
'       True -> 1 (Int32)
'       True -> -1 (Int32)
``````

Para las conversiones de Boolean a valores de cadena, consulte la sección aplicar formato a los valores booleanos .For conversions from Boolean to string values, see the Formatting Boolean Values section. Para obtener las conversiones de cadenas a Boolean valores, vea la sección analizar valores booleanos .For conversions from strings to Boolean values, see the Parsing Boolean Values section.

### Analizar valores booleanosParse Boolean values

La Boolean estructura incluye dos métodos de análisis estáticos, Parse y TryParse , que convierten una cadena en un valor booleano.The Boolean structure includes two static parsing methods, Parse and TryParse, that convert a string to a Boolean value. La representación de cadena de un valor booleano se define mediante los equivalentes que no distinguen mayúsculas de minúsculas de los valores de los TrueString FalseString campos y, que son "true" y "false", respectivamente.The string representation of a Boolean value is defined by the case-insensitive equivalents of the values of the TrueString and FalseString fields, which are "True" and "False", respectively. En otras palabras, las únicas cadenas que se analizan correctamente son "true", "false", "true", "false" o algún equivalente en mayúsculas y minúsculas.In other words, the only strings that parse successfully are "True", "False", "true", "false", or some mixed-case equivalent. No se pueden analizar correctamente cadenas numéricas como "0" o "1".You cannot successfully parse numeric strings such as "0" or "1". Los caracteres de espacio en blanco iniciales o finales no se tienen en cuenta al realizar la comparación de cadenas.Leading or trailing white-space characters are not considered when performing the string comparison.

En el ejemplo siguiente se usan los Parse TryParse métodos y para analizar un número de cadenas.The following example uses the Parse and TryParse methods to parse a number of strings. Tenga en cuenta que solo se pueden analizar correctamente los equivalentes de "true" y "false" que no distinguen mayúsculas de minúsculas.Note that only the case-insensitive equivalents of "True" and "False" can be successfully parsed.

``````using System;

public class Example
{
public static void Main()
{
string[] values = { null, String.Empty, "True", "False",
"true", "false", "    true    ",
"TrUe", "fAlSe", "fa lse", "0",
"1", "-1", "string" };
// Parse strings using the Boolean.Parse method.
foreach (var value in values) {
try {
bool flag = Boolean.Parse(value);
Console.WriteLine("'{0}' --> {1}", value, flag);
}
catch (ArgumentException) {
Console.WriteLine("Cannot parse a null string.");
}
catch (FormatException) {
Console.WriteLine("Cannot parse '{0}'.", value);
}
}
Console.WriteLine();
// Parse strings using the Boolean.TryParse method.
foreach (var value in values) {
bool flag = false;
if (Boolean.TryParse(value, out flag))
Console.WriteLine("'{0}' --> {1}", value, flag);
else
Console.WriteLine("Unable to parse '{0}'", value);
}
}
}
// The example displays the following output:
//       Cannot parse a null string.
//       Cannot parse ''.
//       'True' --> True
//       'False' --> False
//       'true' --> True
//       'false' --> False
//       '    true    ' --> True
//       'TrUe' --> True
//       'fAlSe' --> False
//       Cannot parse 'fa lse'.
//       Cannot parse '0'.
//       Cannot parse '1'.
//       Cannot parse '-1'.
//       Cannot parse 'string'.
//
//       Unable to parse ''
//       Unable to parse ''
//       'True' --> True
//       'False' --> False
//       'true' --> True
//       'false' --> False
//       '    true    ' --> True
//       'TrUe' --> True
//       'fAlSe' --> False
//       Cannot parse 'fa lse'.
//       Unable to parse '0'
//       Unable to parse '1'
//       Unable to parse '-1'
//       Unable to parse 'string'
``````
``````Module Example
Public Sub Main()
Dim values() As String = { Nothing, String.Empty, "True", "False",
"true", "false", "    true    ",
"TrUe", "fAlSe", "fa lse", "0",
"1", "-1", "string" }
' Parse strings using the Boolean.Parse method.
For Each value In values
Try
Dim flag As Boolean = Boolean.Parse(value)
Console.WriteLine("'{0}' --> {1}", value, flag)
Catch e As ArgumentException
Console.WriteLine("Cannot parse a null string.")
Catch e As FormatException
Console.WriteLine("Cannot parse '{0}'.", value)
End Try
Next
Console.WriteLine()
' Parse strings using the Boolean.TryParse method.
For Each value In values
Dim flag As Boolean = False
If Boolean.TryParse(value, flag)
Console.WriteLine("'{0}' --> {1}", value, flag)
Else
Console.WriteLine("Cannot parse '{0}'.", value)
End If
Next
End Sub
End Module
' The example displays the following output:
'       Cannot parse a null string.
'       Cannot parse ''.
'       'True' --> True
'       'False' --> False
'       'true' --> True
'       'false' --> False
'       '    true    ' --> True
'       'TrUe' --> True
'       'fAlSe' --> False
'       Cannot parse 'fa lse'.
'       Cannot parse '0'.
'       Cannot parse '1'.
'       Cannot parse '-1'.
'       Cannot parse 'string'.
'
'       Unable to parse ''
'       Unable to parse ''
'       'True' --> True
'       'False' --> False
'       'true' --> True
'       'false' --> False
'       '    true    ' --> True
'       'TrUe' --> True
'       'fAlSe' --> False
'       Cannot parse 'fa lse'.
'       Unable to parse '0'
'       Unable to parse '1'
'       Unable to parse '-1'
'       Unable to parse 'string'
``````

Si está programando en Visual Basic, puede usar la `CBool` función para convertir la representación de cadena de un número en un valor booleano.If you are programming in Visual Basic, you can use the `CBool` function to convert the string representation of a number to a Boolean value. "0" se convierte en `false` y la representación de cadena de cualquier valor distinto de cero se convierte en `true` ."0" is converted to `false`, and the string representation of any non-zero value is converted to `true`. Si no está programando en Visual Basic, debe convertir la cadena numérica en un número antes de convertirla en un valor booleano.If you are not programming in Visual Basic, you must convert your numeric string to a number before converting it to a Boolean. En el ejemplo siguiente se muestra cómo convertir una matriz de enteros en valores booleanos.The following example illustrates this by converting an array of integers to Boolean values.

``````using System;

public class Example
{
public static void Main()
{
String[] values = { "09", "12.6", "0", "-13 " };
foreach (var value in values) {
bool success, result;
int number;
success = Int32.TryParse(value, out number);
if (success) {
// The method throws no exceptions.
result = Convert.ToBoolean(number);
Console.WriteLine("Converted '{0}' to {1}", value, result);
}
else {
Console.WriteLine("Unable to convert '{0}'", value);
}
}
}
}
// The example displays the following output:
//       Converted '09' to True
//       Unable to convert '12.6'
//       Converted '0' to False
//       Converted '-13 ' to True
``````
``````Module Example
Public Sub Main()
Dim values() As String = { "09", "12.6", "0", "-13 " }
For Each value In values
Dim success, result As Boolean
Dim number As Integer
success = Int32.TryParse(value, number)
If success Then
' The method throws no exceptions.
result = Convert.ToBoolean(number)
Console.WriteLine("Converted '{0}' to {1}", value, result)
Else
Console.WriteLine("Unable to convert '{0}'", value)
End If
Next
End Sub
End Module
' The example displays the following output:
'       Converted '09' to True
'       Unable to convert '12.6'
'       Converted '0' to False
'       Converted '-13 ' to True
``````

### Comparar valores booleanosCompare Boolean values

Dado que los valores booleanos son `true` o `false` , hay pocos motivos para llamar explícitamente al CompareTo método, que indica si una instancia es mayor, menor o igual que un valor especificado.Because Boolean values are either `true` or `false`, there is little reason to explicitly call the CompareTo method, which indicates whether an instance is greater than, less than, or equal to a specified value. Normalmente, para comparar dos variables Booleanas, se llama al Equals método o se usa el operador de igualdad del lenguaje.Typically, to compare two Boolean variables, you call the Equals method or use your language's equality operator.

Sin embargo, si desea comparar una variable booleana con el valor booleano literal `true` o `false` , no es necesario realizar una comparación explícita, ya que el resultado de la evaluación de un valor booleano es ese valor booleano.However, when you want to compare a Boolean variable with the literal Boolean value `true` or `false`, it is not necessary to do an explicit comparison, because the result of evaluating a Boolean value is that Boolean value. Por ejemplo, las expresionesFor example, the expressions

``````if (booleanValue == true) {
``````
``````If booleanValue = True Then
``````

yand

``````if (booleanValue) {
``````
``````If booleanValue Then
``````

son equivalentes, pero la segunda es más compacta.are equivalent, but the second is more compact. Sin embargo, ambas técnicas ofrecen un rendimiento comparable.However, both techniques offer comparable performance.

### Trabajar con valores booleanos como valores binariosWork with Booleans as binary values

Un valor booleano ocupa un byte de memoria, como se muestra en el siguiente ejemplo de C#.A Boolean value occupies one byte of memory, as the following C# example shows. El ejemplo se debe compilar con el `/unsafe` modificador.The example must be compiled with the `/unsafe` switch.

``````using System;

public struct BoolStruct
{
public bool flag1;
public bool flag2;
public bool flag3;
public bool flag4;
public bool flag5;
}

public class Example
{
public static void Main()
{
unsafe {
BoolStruct b = new BoolStruct();
Console.WriteLine("Size of BoolStruct: {0}", sizeof(BoolStruct));
Console.WriteLine("Field offsets:");
Console.WriteLine("   flag1: {0}", (bool*) &b.flag1 - addr);
Console.WriteLine("   flag1: {0}", (bool*) &b.flag2 - addr);
Console.WriteLine("   flag1: {0}", (bool*) &b.flag3 - addr);
Console.WriteLine("   flag1: {0}", (bool*) &b.flag4 - addr);
Console.WriteLine("   flag1: {0}", (bool*) &b.flag5 - addr);
}
}
}
// The example displays the following output:
//       Size of BoolStruct: 5
//       Field offsets:
//          flag1: 0
//          flag1: 1
//          flag1: 2
//          flag1: 3
//          flag1: 4
``````

El bit de orden inferior del byte se utiliza para representar su valor.The byte's low-order bit is used to represent its value. Un valor de 1 representa `true` ; un valor de 0 representa `false` .A value of 1 represents `true`; a value of 0 represents `false`.

Sugerencia

Puede utilizar la System.Collections.Specialized.BitVector32 estructura para trabajar con conjuntos de valores booleanos.You can use the System.Collections.Specialized.BitVector32 structure to work with sets of Boolean values.

Puede convertir un valor booleano en su representación binaria llamando al BitConverter.GetBytes(Boolean) método.You can convert a Boolean value to its binary representation by calling the BitConverter.GetBytes(Boolean) method. El método devuelve una matriz de bytes con un solo elemento.The method returns a byte array with a single element. Para restaurar un valor booleano a partir de su representación binaria, puede llamar al BitConverter.ToBoolean(Byte[], Int32) método.To restore a Boolean value from its binary representation, you can call the BitConverter.ToBoolean(Byte[], Int32) method.

En el ejemplo siguiente se llama al BitConverter.GetBytes método para convertir un valor booleano en su representación binaria y se muestran los bits individuales del valor y, a continuación, se llama al BitConverter.ToBoolean método para restaurar el valor desde su representación binaria.The following example calls the BitConverter.GetBytes method to convert a Boolean value to its binary representation and displays the individual bits of the value, and then calls the BitConverter.ToBoolean method to restore the value from its binary representation.

``````using System;

public class Example
{
public static void Main()
{
bool[] flags = { true, false };
foreach (var flag in flags) {
// Get binary representation of flag.
Byte value = BitConverter.GetBytes(flag)[0];
Console.WriteLine("Original value: {0}", flag);
Console.WriteLine("Binary value:   {0} ({1})", value,
GetBinaryString(value));
// Restore the flag from its binary representation.
bool newFlag = BitConverter.ToBoolean( new Byte[] { value }, 0);
Console.WriteLine("Restored value: {0}\n", flag);
}
}

private static string GetBinaryString(Byte value)
{
String retVal = Convert.ToString(value, 2);
return new String('0', 8 - retVal.Length) + retVal;
}
}
// The example displays the following output:
//       Original value: True
//       Binary value:   1 (00000001)
//       Restored value: True
//
//       Original value: False
//       Binary value:   0 (00000000)
//       Restored value: False
``````
``````Module Example
Public Sub Main()
Dim flags() As Boolean = { True, False }
For Each flag In flags
' Get binary representation of flag.
Dim value As Byte = BitConverter.GetBytes(flag)(0)
Console.WriteLine("Original value: {0}", flag)
Console.WriteLine("Binary value:   {0} ({1})", value,
GetBinaryString(value))
' Restore the flag from its binary representation.
Dim newFlag As Boolean = BitConverter.ToBoolean( { value }, 0)
Console.WriteLine("Restored value: {0}", flag)
Console.WriteLine()
Next
End Sub

Private Function GetBinaryString(value As Byte) As String
Dim retVal As String = Convert.ToString(value, 2)
Return New String("0"c, 8 - retVal.Length) + retVal
End Function
End Module
' The example displays the following output:
'       Original value: True
'       Binary value:   1 (00000001)
'       Restored value: True
'
'       Original value: False
'       Binary value:   0 (00000000)
'       Restored value: False
``````

### Realizar operaciones con valores booleanosPerform operations with Boolean values

En esta sección se muestra cómo se usan los valores booleanos en las aplicaciones.This section illustrates how Boolean values are used in apps. En la primera sección se describe su uso como una marca.The first section discusses its use as a flag. En el segundo se muestra su uso para las operaciones aritméticas.The second illustrates its use for arithmetic operations.

#### Valores booleanos como marcasBoolean values as flags

Las variables Booleanas se usan normalmente como marcas para indicar la presencia o ausencia de alguna condición.Boolean variables are most commonly used as flags, to signal the presence or absence of some condition. Por ejemplo, en el String.Compare(String, String, Boolean) método, el parámetro final, `ignoreCase` , es una marca que indica si la comparación de dos cadenas distingue entre mayúsculas y minúsculas ( `ignoreCase` is `true` ) o distingue entre mayúsculas y minúsculas ( `ignoreCase` es `false` ).For example, in the String.Compare(String, String, Boolean) method, the final parameter, `ignoreCase`, is a flag that indicates whether the comparison of two strings is case-insensitive (`ignoreCase` is `true`) or case-sensitive (`ignoreCase` is `false`). Después, el valor de la marca se puede evaluar en una instrucción condicional.The value of the flag can then be evaluated in a conditional statement.

En el ejemplo siguiente se usa una aplicación de consola simple para mostrar el uso de variables Booleanas como marcas.The following example uses a simple console app to illustrate the use of Boolean variables as flags. La aplicación acepta parámetros de línea de comandos que permiten redirigir la salida a un archivo especificado (el `/f` modificador) y que permite enviar la salida a un archivo especificado y a la consola (el `/b` conmutador).The app accepts command-line parameters that enable output to be redirected to a specified file (the `/f` switch), and that enable output to be sent both to a specified file and to the console (the `/b` switch). La aplicación define una marca denominada `isRedirected` para indicar si se va a enviar la salida a un archivo y una marca denominada `isBoth` para indicar que se debe enviar la salida a la consola.The app defines a flag named `isRedirected` to indicate whether output is to be sent to a file, and a flag named `isBoth` to indicate that output should be sent to the console.

``````using System;
using System.IO;

public class Example
{
public static void Main()
{
// Initialize flag variables.
bool isRedirected = false;
bool isBoth = false;
String fileName = "";
StreamWriter sw = null;

// Get any command line arguments.
String[] args = Environment.GetCommandLineArgs();
// Handle any arguments.
if (args.Length > 1) {
for (int ctr = 1; ctr < args.Length; ctr++) {
String arg = args[ctr];
if (arg.StartsWith("/") || arg.StartsWith("-")) {
switch (arg.Substring(1).ToLower())
{
case "f":
isRedirected = true;
if (args.Length < ctr + 2) {
ShowSyntax("The /f switch must be followed by a filename.");
return;
}
fileName = args[ctr + 1];
ctr++;
break;
case "b":
isBoth = true;
break;
default:
ShowSyntax(String.Format("The {0} switch is not supported",
args[ctr]));
return;
}
}
}
}

// If isBoth is True, isRedirected must be True.
if (isBoth &&  ! isRedirected) {
ShowSyntax("The /f switch must be used if /b is used.");
return;
}

// Handle output.
if (isRedirected) {
sw = new StreamWriter(fileName);
if (!isBoth)
Console.SetOut(sw);
}
String msg = String.Format("Application began at {0}", DateTime.Now);
Console.WriteLine(msg);
if (isBoth) sw.WriteLine(msg);
msg = String.Format("Application ended normally at {0}", DateTime.Now);
Console.WriteLine(msg);
if (isBoth) sw.WriteLine(msg);
if (isRedirected) sw.Close();
}

private static void ShowSyntax(String errMsg)
{
Console.WriteLine(errMsg);
Console.WriteLine("\nSyntax: Example [[/f <filename> [/b]]\n");
}
}
``````
``````Imports System.IO

Module Example
Public Sub Main()
' Initialize flag variables.
Dim isRedirected, isBoth As Boolean
Dim fileName As String = ""
Dim sw As StreamWriter = Nothing

' Get any command line arguments.
Dim args() As String = Environment.GetCommandLineArgs()
' Handle any arguments.
If args.Length > 1 Then
For ctr = 1 To args.Length - 1
Dim arg As String = args(ctr)
If arg.StartsWith("/") OrElse arg.StartsWith("-") Then
Select Case arg.Substring(1).ToLower()
Case "f"
isRedirected = True
If args.Length < ctr + 2 Then
ShowSyntax("The /f switch must be followed by a filename.")
Exit Sub
End If
fileName = args(ctr + 1)
ctr += 1
Case "b"
isBoth = True
Case Else
ShowSyntax(String.Format("The {0} switch is not supported",
args(ctr)))
Exit Sub
End Select
End If
Next
End If

' If isBoth is True, isRedirected must be True.
If isBoth And Not isRedirected Then
ShowSyntax("The /f switch must be used if /b is used.")
Exit Sub
End If

' Handle output.
If isRedirected Then
sw = New StreamWriter(fileName)
If Not IsBoth Then
Console.SetOut(sw)
End If
End If
Dim msg As String = String.Format("Application began at {0}", Date.Now)
Console.WriteLine(msg)
If isBoth Then sw.WriteLine(msg)
msg = String.Format("Application ended normally at {0}", Date.Now)
Console.WriteLine(msg)
If isBoth Then sw.WriteLine(msg)
If isRedirected Then sw.Close()
End Sub

Private Sub ShowSyntax(errMsg As String)
Console.WriteLine(errMsg)
Console.WriteLine()
Console.WriteLine("Syntax: Example [[/f <filename> [/b]]")
Console.WriteLine()
End Sub
End Module
``````

#### Booleanos y operaciones aritméticasBooleans and arithmetic operations

A veces se utiliza un valor booleano para indicar la presencia de una condición que desencadena un cálculo matemático.A Boolean value is sometimes used to indicate the presence of a condition that triggers a mathematical calculation. Por ejemplo, una `hasShippingCharge` variable podría servir como una marca para indicar si se van a agregar cargos de envío a una cantidad de factura.For example, a `hasShippingCharge` variable might serve as a flag to indicate whether to add shipping charges to an invoice amount.

Dado que una operación con un `false` valor no tiene ningún efecto en el resultado de una operación, no es necesario convertir el valor booleano en un valor entero para usarlo en la operación matemática.Because an operation with a `false` value has no effect on the result of an operation, it is not necessary to convert the Boolean to an integral value to use in the mathematical operation. En su lugar, puede usar la lógica condicional.Instead, you can use conditional logic.

En el ejemplo siguiente se calcula una cantidad que se compone de un subtotal, un cargo de envío y un cargo de servicio opcional.The following example computes an amount that consists of a subtotal, a shipping charge, and an optional service charge. La `hasServiceCharge` variable determina si se aplica el cargo del servicio.The `hasServiceCharge` variable determines whether the service charge is applied. En lugar de convertirlo `hasServiceCharge` en un valor numérico y multiplicarlo por la cantidad del cargo del servicio, en el ejemplo se usa la lógica condicional para agregar la cantidad de cargo del servicio si es aplicable.Instead of converting `hasServiceCharge` to a numeric value and multiplying it by the amount of the service charge, the example uses conditional logic to add the service charge amount if it is applicable.

``````using System;

public class Example
{
public static void Main()
{
bool[] hasServiceCharges = { true, false };
Decimal subtotal = 120.62m;
Decimal shippingCharge = 2.50m;
Decimal serviceCharge = 5.00m;

foreach (var hasServiceCharge in hasServiceCharges) {
Decimal total = subtotal + shippingCharge +
(hasServiceCharge ? serviceCharge : 0);
Console.WriteLine("hasServiceCharge = {1}: The total is {0:C2}.",
total, hasServiceCharge);
}
}
}
// The example displays output like the following:
//       hasServiceCharge = True: The total is \$128.12.
//       hasServiceCharge = False: The total is \$123.12.
``````
``````Module Example
Public Sub Main()
Dim hasServiceCharges() As Boolean = { True, False }
Dim subtotal As Decimal = 120.62d
Dim shippingCharge As Decimal = 2.50d
Dim serviceCharge As Decimal = 5.00d

For Each hasServiceCharge In hasServiceCharges
Dim total As Decimal = subtotal + shippingCharge +
If(hasServiceCharge, serviceCharge, 0)
Console.WriteLine("hasServiceCharge = {1}: The total is {0:C2}.",
total, hasServiceCharge)
Next
End Sub
End Module
' The example displays output like the following:
'       hasServiceCharge = True: The total is \$128.12.
'       hasServiceCharge = False: The total is \$123.12.
``````

#### Booleanos e interoperabilidadBooleans and interop

Aunque el cálculo de referencias de tipos de datos base a COM suele ser sencillo, el Boolean tipo de datos es una excepción.While marshaling base data types to COM is generally straightforward, the Boolean data type is an exception. Puede aplicar el MarshalAsAttribute atributo para calcular las referencias del Boolean tipo en cualquiera de las representaciones siguientes:You can apply the MarshalAsAttribute attribute to marshal the Boolean type to any of the following representations:

UnmanagedType.Bool Valor entero de 4 bytes, donde cualquier valor distinto de cero representa `true` y 0 representa `false` .A 4-byte integer value, where any nonzero value represents `true` and 0 represents `false`. Este es el formato predeterminado de un Boolean campo en una estructura y de un Boolean parámetro en las llamadas de invocación de plataforma.This is the default format of a Boolean field in a structure and of a Boolean parameter in platform invoke calls.
UnmanagedType.U1 Valor entero de 1 byte, donde 1 representa `true` y 0 representa `false` .A 1-byte integer value, where the 1 represents `true` and 0 represents `false`.
UnmanagedType.VariantBool Valor entero de 2 bytes, donde-1 representa `true` y 0 representa `false` .A 2-byte integer value, where -1 represents `true` and 0 represents `false`. Este es el formato predeterminado de un Boolean parámetro en las llamadas de interoperabilidad com.This is the default format of a Boolean parameter in COM interop calls.

## Campos

 Representa el valor booleano `false` como una cadena.Represents the Boolean value `false` as a string. Este campo es de solo lectura.This field is read-only. Representa el valor booleano `true` como una cadena.Represents the Boolean value `true` as a string. Este campo es de solo lectura.This field is read-only.