Visual Studio 2010 - Visual Basic Option Infer Statement Enables the use of local type inference in declaring variables.
Option Infer { On | Off }

Parts
Term | Definition | On | Optional. Enables local type inference. | Off | Optional. Disables local type inference. |

Remarks
To set Option Infer in a file, type Option Infer On or Option Infer Off at the top of the file, before any other source code. If the value set for Option Infer in a file conflicts with the value set in the IDE or on the command line, the value in the file has precedence. When you set Option Infer to On, you can declare local variables without explicitly stating a data type. The compiler infers the data type of a variable from the type of its initialization expression. In the following illustration, Option Infer is turned on. The variable in the declaration Dim someVar = 2 is declared as an integer by type inference. IntelliSense when Option Infer is on .png) In the following illustration, Option Infer is turned off. The variable in the declaration Dim someVar = 2 is declared as an Object by type inference. In this example, the Option Strict setting is set to Off on the Compile Page, Project Designer (Visual Basic). IntelliSense when Option Infer is off .png) When a variable is declared as an Object, the run-time type can change while the program is running. Visual Basic performs operations called boxing and unboxing to convert between an Object and a value type. These operations make execution slower. For information about boxing and unboxing, see the Visual Basic Language Specification. Type inference applies at the procedure level, and does not apply outside a procedure in a class, structure, module, or interface. For additional information, see Local Type Inference (Visual Basic). When an Option Infer Statement Is Not PresentIf the source code does not contain an Option Infer statement, the Option Infer setting on the Compile Page, Project Designer (Visual Basic) is used. If the command-line compiler is used, the /optioninfer compiler option is used. To set Option Infer in the IDEIn Solution Explorer, select a project. On the Project menu, click Properties. For more information, see Introduction to the Project Designer. Click the Compile tab. Set the value in the Option infer box.
When you create a new project, the Option Infer setting on the Compile tab is set to the Option Infer setting in the VB Defaults dialog box. To access the VB Defaults dialog box, on the Tools menu, click Options. In the Options dialog box, expand Projects and Solutions, and then click VB Defaults. The initial default setting in VB Defaults is On. To set Option Infer on the command lineDefault Data Types and ValuesThe following table describes the results of various combinations of specifying the data type and initializer in a Dim statement. Data type specified? | Initializer specified? | Example | Result | No | No | Dim qty | If Option Strict is off (the default), the variable is set to Nothing. If Option Strict is on, a compile-time error occurs. | No | Yes | Dim qty = 5 | If Option Infer is on (the default), the variable takes the data type of the initializer. See Local Type Inference (Visual Basic). If Option Infer is off and Option Strict is off, the variable takes the data type of Object. If Option Infer is off and Option Strict is on, a compile-time error occurs. | Yes | No | Dim qty As Integer | The variable is initialized to the default value for the data type. For more information, see Dim Statement (Visual Basic). | Yes | Yes | Dim qty
As Integer = 5 | If the data type of the initializer is not convertible to the specified data type, a compile-time error occurs. |

Example
The following examples demonstrate how the Option Infer statement enables local type inference.
' Enable Option Infer before trying these examples.
' Variable num is an Integer.
Dim num = 5
' Variable dbl is a Double.
Dim dbl = 4.113
' Variable str is a String.
Dim str = "abc"
' Variable pList is an array of Process objects.
Dim pList = Process.GetProcesses()
' Variable i is an Integer.
For i = 1 To 10
Console.WriteLine(i)
Next
' Variable item is a string.
Dim lst As New List(Of String) From {"abc", "def", "ghi"}
For Each item In lst
Console.WriteLine(item)
Next
' Variable namedCust is an instance of the Customer class.
Dim namedCust = New Customer With {.Name = "Blue Yonder Airlines",
.City = "Snoqualmie"}
' Variable product is an instance of an anonymous type.
Dim product = New With {Key .Name = "paperclips", .Price = 1.29}
' If customers is a collection of Customer objects in the following
' query, the inferred type of cust is Customer, and the inferred type
' of custs is IEnumerable(Of Customer).
Dim custs = From cust In customers
Where cust.City = "Seattle"
Select cust.Name, cust.ID
The following example demonstrates that the run-time type can differ when a variable is identified as an Object.
' Disable Option Infer when trying this example.
Dim someVar = 5
Console.WriteLine(someVar.GetType.ToString)
' If Option Infer is instead enabled, the following
' statement causes a run-time error. This is because
' someVar was implicitly defined as an integer.
someVar = "abc"
Console.WriteLine(someVar.GetType.ToString)
' Output:
' System.Int32
' System.String

See Also

Change History
Date | History | Reason |
April 2011
| Added information about the Object type, and about type inference. |
Information enhancement.
|
March 2011
| Modified the remarks and added an example. |
Information enhancement.
|
|
Visual Studio 2010 - Visual Basic Option Infer (instrucción) Habilita el uso de la inferencia de tipo de variable local al declarar las variables.
Option Infer { On | Off }

Partes
Término | Definición | On | Opcional. Habilita la inferencia de tipo de variable local. | Off | Opcional. Deshabilita la inferencia de tipo de variable local. |

Comentarios
Para establecer Option Infer en un archivo, escriba Option Infer On o Option Infer Off en la parte superior del archivo, antes de cualquier otro código fuente. Si el valor que se establece para Option Infer en un archivo está en conflicto con el valor establecido en el IDE o la línea de comandos, tiene prioridad el valor del archivo. Al establecer Option Infer en On, puede declarar las variables locales sin especificar explícitamente un tipo de datos. El compilador deduce el tipo de datos de una variable a partir del tipo de su expresión de inicialización. En la siguiente ilustración, Option Infer está activada. La variable de la declaración Dim someVar = 2 se declara como un entero por inferencia de tipos. IntelliSense cuando está activada la instrucción Option Infer .png) En la siguiente ilustración, Option Infer está desactivada. La variable de la declaración Dim someVar = 2 se declara como un Object por inferencia de tipos. En este ejemplo, el valor de Option Strict se establece en Off en Página Compilación, Diseñador de proyectos (Visual Basic). IntelliSense cuando está desactivada la instrucción Option Infer .png) Cuando se declara una variable como un Object, puede cambiar el tipo en tiempo de ejecución mientras se ejecuta el programa. Visual Basic realiza operaciones llamadas conversión boxing y conversión unboxing para convertir entre un Object y un tipo de valor. Estas operaciones ralentizan la ejecución. Para obtener información acerca de las conversiones boxing y unboxing, vea Especificación del lenguaje de Visual Basic. La inferencia de tipos se aplica en el nivel de procedimiento, y no se aplica fuera de un procedimiento en una clase, estructura, módulo o interfaz. Para obtener información adicional, vea Inferencia de tipo de variable local (Visual Basic). Cuando no existe una instrucción Option InferSi el código fuente no contiene una instrucción Option Infer, se utiliza el valor de Option Infer en Página Compilación, Diseñador de proyectos (Visual Basic). Si se utiliza el compilador de línea de comandos, se utiliza la opción del compilador /optioninfer. Para establecer Option Infer en el IDEEn el Explorador de soluciones, seleccione un proyecto. En el menú Proyecto, haga clic en Propiedades. Para obtener más información, vea Introducción al Diseñador de proyectos. Haga clic en la ficha Compilar. Establezca el valor en la casilla Option infer.
Cuando se crea un nuevo proyecto, el valor de Option Infer en la pestaña Compilación se establece en el valor de Option Infer en el cuadro de diálogo Valores predeterminados de VB. Para obtener acceso al cuadro de diálogo Valores predeterminados de VB, en el menú Herramientas, haga clic en Opciones. En el cuadro de diálogo Opciones, expanda Proyectos y soluciones y, a continuación, haga clic en Valores predeterminados de VB. El valor predeterminado inicial de Valores predeterminados de VB es On. Para establecer Option Infer en la línea de comandosValores y tipos de datos predeterminadosLa tabla siguiente describe los resultados de varias combinaciones de especificar el tipo de datos y el inicializador en una instrucción Dim. ¿Tipo de datos especificado? | ¿Inicializador especificado? | Ejemplo | Resultado | No | No | Dim qty | Si Option Strict está desactivada (el valor predeterminado), la variable se establece en Nothing. Si Option Strict está activada, se produce un error en tiempo de compilación. | No | Sí | Dim qty = 5 | Si Option Infer está activada (el valor predeterminado), la variable toma el tipo de datos del inicializador. Vea Inferencia de tipo de variable local (Visual Basic). Si Option Infer y Option Strict están desactivadas, la variable toma el tipo de datos de Object. Si Option Infer está desactivada y Option Strict está activada, se produce un error en tiempo de compilación. | Sí | No | Dim qty As Integer | La variable se inicializa con el valor predeterminado para el tipo de datos. Para obtener más información, vea Instrucción Dim (Visual Basic). | Sí | Sí | Dim qty
As Integer = 5 | Si el tipo de datos del inicializador no es convertible al tipo de datos especificado, se produce un error en tiempo de compilación. |

Ejemplo
En los ejemplos siguientes se muestra cómo la instrucción Option Infer habilita la inferencia de tipo de variable local.
' Enable Option Infer before trying these examples.
' Variable num is an Integer.
Dim num = 5
' Variable dbl is a Double.
Dim dbl = 4.113
' Variable str is a String.
Dim str = "abc"
' Variable pList is an array of Process objects.
Dim pList = Process.GetProcesses()
' Variable i is an Integer.
For i = 1 To 10
Console.WriteLine(i)
Next
' Variable item is a string.
Dim lst As New List(Of String) From {"abc", "def", "ghi"}
For Each item In lst
Console.WriteLine(item)
Next
' Variable namedCust is an instance of the Customer class.
Dim namedCust = New Customer With {.Name = "Blue Yonder Airlines",
.City = "Snoqualmie"}
' Variable product is an instance of an anonymous type.
Dim product = New With {Key .Name = "paperclips", .Price = 1.29}
' If customers is a collection of Customer objects in the following
' query, the inferred type of cust is Customer, and the inferred type
' of custs is IEnumerable(Of Customer).
Dim custs = From cust In customers
Where cust.City = "Seattle"
Select cust.Name, cust.ID
El ejemplo siguiente demuestra que el tipo en tiempo de ejecución puede variar cuando se identifica una variable como un Object.
' Disable Option Infer when trying this example.
Dim someVar = 5
Console.WriteLine(someVar.GetType.ToString)
' If Option Infer is instead enabled, the following
' statement causes a run-time error. This is because
' someVar was implicitly defined as an integer.
someVar = "abc"
Console.WriteLine(someVar.GetType.ToString)
' Output:
' System.Int32
' System.String

Vea también

Historial de cambios
Fecha | Historial | Motivo |
1 de abril de 2011
| Información adicional acerca del tipo Object y sobre la inferencia de tipos. |
Mejora de la información.
|
Marzo de 2011
| Modificadas las observaciones y agregado un ejemplo. |
Mejora de la información.
|
|