diff --git a/docs/core/tutorials/with-visual-studio-code.md b/docs/core/tutorials/with-visual-studio-code.md index c4ed5bd27ded8..0b7508f2484db 100644 --- a/docs/core/tutorials/with-visual-studio-code.md +++ b/docs/core/tutorials/with-visual-studio-code.md @@ -83,7 +83,7 @@ Enhance the application to prompt the user for their name and display it along w 1. Replace the contents of the `Main` method in *Program.cs*, which is the line that calls `Console.WriteLine`, with the following code: - :::code language="csharp" source="./snippets/with-visual-studio/csharp/Program.cs" id="Snippet1"::: + :::code language="csharp" source="./snippets/with-visual-studio/csharp/Program.cs" id="1"::: This code displays "What is your name?" in the console window and waits until the user enters a string followed by the Enter key. It stores this string in a variable named `name`. It also retrieves the value of the property, which contains the current local time, and assigns it to a variable named `date`. Finally, it displays these values in the console window. diff --git a/docs/core/tutorials/with-visual-studio-mac.md b/docs/core/tutorials/with-visual-studio-mac.md index f246d1af66441..4381da60a49e2 100644 --- a/docs/core/tutorials/with-visual-studio-mac.md +++ b/docs/core/tutorials/with-visual-studio-mac.md @@ -78,7 +78,7 @@ Enhance the application to prompt the user for their name and display it along w 1. In *Program.cs*, replace the contents of the `Main` method, which is the line that calls `Console.WriteLine`, with the following code: - :::code language="csharp" source="./snippets/with-visual-studio/csharp/Program.cs" id="Snippet1"::: + :::code language="csharp" source="./snippets/with-visual-studio/csharp/Program.cs" id="1"::: This code displays "What is your name?" in the console window and waits until the user enters a string followed by the enter key. It stores this string in a variable named `name`. It also retrieves the value of the property, which contains the current local time, and assigns it to a variable named `date`. Finally, it displays these values in the console window. diff --git a/docs/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern.md b/docs/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern.md index c27ba2e1b06ac..d4678ced229fa 100644 --- a/docs/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern.md +++ b/docs/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern.md @@ -221,7 +221,7 @@ string [] pages = await Task.WhenAll( You can use the same exception-handling techniques we discussed in the previous void-returning scenario: ```csharp -Task [] asyncOps = +Task [] asyncOps = (from url in urls select DownloadStringAsync(url)).ToArray(); try { diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.AsyncInterop/vb/Wrap1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.AsyncInterop/vb/Wrap1.vb index 4c0da78f126e7..9a0e6c2afd517 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.AsyncInterop/vb/Wrap1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.AsyncInterop/vb/Wrap1.vb @@ -8,15 +8,15 @@ Imports System.Threading.Tasks Module Example ' - Public Function ReadAsync(strm As Stream, - buffer As Byte(), offset As Integer, + Public Function ReadAsync(strm As Stream, + buffer As Byte(), offset As Integer, count As Integer) As Task(Of Integer) - If strm Is Nothing Then - Throw New ArgumentNullException("stream") - End If - - Return Task(Of Integer).Factory.FromAsync(AddressOf strm.BeginRead, - AddressOf strm.EndRead, buffer, + If strm Is Nothing Then + Throw New ArgumentNullException("stream") + End If + + Return Task(Of Integer).Factory.FromAsync(AddressOf strm.BeginRead, + AddressOf strm.EndRead, buffer, offset, count, Nothing) End Function ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.AsyncInterop/vb/Wrap2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.AsyncInterop/vb/Wrap2.vb index 54e34eb99c06e..44227d6a07999 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.AsyncInterop/vb/Wrap2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.AsyncInterop/vb/Wrap2.vb @@ -12,23 +12,23 @@ Module Example Public Function ReadAsync(stream As Stream, buffer As Byte(), _ offset As Integer, count As Integer) _ As Task(Of Integer) - If stream Is Nothing Then - Throw New ArgumentNullException("stream") - End If + If stream Is Nothing Then + Throw New ArgumentNullException("stream") + End If - Dim tcs As New TaskCompletionSource(Of Integer)() - stream.BeginRead(buffer, offset, count, - Sub(iar) - Try - tcs.TrySetResult(stream.EndRead(iar)) - Catch e As OperationCanceledException - tcs.TrySetCanceled() - Catch e As Exception - tcs.TrySetException(e) - End Try - End Sub, Nothing) - Return tcs.Task - End Function - ' + Dim tcs As New TaskCompletionSource(Of Integer)() + stream.BeginRead(buffer, offset, count, + Sub(iar) + Try + tcs.TrySetResult(stream.EndRead(iar)) + Catch e As OperationCanceledException + tcs.TrySetCanceled() + Catch e As Exception + tcs.TrySetException(e) + End Try + End Sub, Nothing) + Return tcs.Task + End Function + ' End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.Interop.PInvoke/vb/Example1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.Interop.PInvoke/vb/Example1.vb index 55190d49e09b6..e59328510718d 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.Interop.PInvoke/vb/Example1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.Interop.PInvoke/vb/Example1.vb @@ -7,7 +7,7 @@ Public Class Win32 ByVal caption As String, ByVal Typ As Integer) As IntPtr End Class -Public Class HelloWorld +Public Class HelloWorld Public Shared Sub Main() Win32.MessageBox(0, "Hello World", "Platform Invoke Sample", 0) End Sub diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/Example.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/Example.vb index f0376d61215d3..5848386cac4dc 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/Example.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/Example.vb @@ -7,80 +7,80 @@ Imports System.Text Module Example - Public Sub Main() - InstantiateStringBuilder() - InstantiateWithCapacity() - Appending() - AppendingFormat() - Inserting() - Removing() - Replacing() - End Sub - - Private Sub InstantiateStringBuilder() - ' - Dim myStringBuilder As New StringBuilder("Hello World!") - ' - End Sub - - Private Sub InstantiateWithCapacity() - ' - Dim myStringBuilder As New StringBuilder("Hello World!", 25) - ' - ' - myStringBuilder.Capacity = 25 - ' - End Sub - - Private Sub Appending() - ' - Dim myStringBuilder As New StringBuilder("Hello World!") - myStringBuilder.Append(" What a beautiful day.") - Console.WriteLine(myStringBuilder) - ' The example displays the following output: - ' Hello World! What a beautiful day. - ' - End Sub + Public Sub Main() + InstantiateStringBuilder() + InstantiateWithCapacity() + Appending() + AppendingFormat() + Inserting() + Removing() + Replacing() + End Sub - Private Sub AppendingFormat() - ' - Dim MyInt As Integer = 25 - Dim myStringBuilder As New StringBuilder("Your total is ") - myStringBuilder.AppendFormat("{0:C} ", MyInt) - Console.WriteLine(myStringBuilder) - ' The example displays the following output: - ' Your total is $25.00 - ' - End Sub + Private Sub InstantiateStringBuilder() + ' + Dim myStringBuilder As New StringBuilder("Hello World!") + ' + End Sub - Private Sub Inserting() - ' - Dim myStringBuilder As New StringBuilder("Hello World!") - myStringBuilder.Insert(6, "Beautiful ") - Console.WriteLine(myStringBuilder) - ' The example displays the following output: - ' Hello Beautiful World! - ' - End Sub + Private Sub InstantiateWithCapacity() + ' + Dim myStringBuilder As New StringBuilder("Hello World!", 25) + ' + ' + myStringBuilder.Capacity = 25 + ' + End Sub - Private Sub Removing() - ' - Dim myStringBuilder As New StringBuilder("Hello World!") - myStringBuilder.Remove(5, 7) - Console.WriteLine(myStringBuilder) - ' The example displays the following output: - ' Hello - ' - End Sub - - Private Sub Replacing() - ' - Dim myStringBuilder As New StringBuilder("Hello World!") - myStringBuilder.Replace("!"c, "?"c) - Console.WriteLine(myStringBuilder) - ' The example displays the following output: - ' Hello World? - ' - End Sub + Private Sub Appending() + ' + Dim myStringBuilder As New StringBuilder("Hello World!") + myStringBuilder.Append(" What a beautiful day.") + Console.WriteLine(myStringBuilder) + ' The example displays the following output: + ' Hello World! What a beautiful day. + ' + End Sub + + Private Sub AppendingFormat() + ' + Dim MyInt As Integer = 25 + Dim myStringBuilder As New StringBuilder("Your total is ") + myStringBuilder.AppendFormat("{0:C} ", MyInt) + Console.WriteLine(myStringBuilder) + ' The example displays the following output: + ' Your total is $25.00 + ' + End Sub + + Private Sub Inserting() + ' + Dim myStringBuilder As New StringBuilder("Hello World!") + myStringBuilder.Insert(6, "Beautiful ") + Console.WriteLine(myStringBuilder) + ' The example displays the following output: + ' Hello Beautiful World! + ' + End Sub + + Private Sub Removing() + ' + Dim myStringBuilder As New StringBuilder("Hello World!") + myStringBuilder.Remove(5, 7) + Console.WriteLine(myStringBuilder) + ' The example displays the following output: + ' Hello + ' + End Sub + + Private Sub Replacing() + ' + Dim myStringBuilder As New StringBuilder("Hello World!") + myStringBuilder.Replace("!"c, "?"c) + Console.WriteLine(myStringBuilder) + ' The example displays the following output: + ' Hello World? + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/example2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/example2.vb index d84ee9010fa10..7287023f56e8d 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/example2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/example2.vb @@ -5,7 +5,7 @@ Imports System.Text Public Class CharsToStr Public Shared Sub Main() Dim sb As New StringBuilder("Start with a string and add from ") - Dim b() As Char = { "c", "h", "a", "r", ".", " ", "B", "u", "t", " ", "n", "o", "t", " ", "a", "l", "l" } + Dim b() As Char = {"c", "h", "a", "r", ".", " ", "B", "u", "t", " ", "n", "o", "t", " ", "a", "l", "l"} Using sw As StringWriter = New StringWriter(sb) ' Write five characters from the array into the StringBuilder. diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/tostringexample1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/tostringexample1.vb index d7d9bf1f4a55a..8fc085b283e34 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/tostringexample1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/tostringexample1.vb @@ -4,23 +4,23 @@ Option Strict On Imports System.Text Module Example - Public Sub Main() - Dim sb As New StringBuilder() - Dim flag As Boolean = True - Dim spellings() As String = { "recieve", "receeve", "receive" } - sb.AppendFormat("Which of the following spellings is {0}:", flag) - sb.AppendLine() - For ctr As Integer = 0 To spellings.GetUpperBound(0) - sb.AppendFormat(" {0}. {1}", ctr, spellings(ctr)) - sb.AppendLine() - Next - sb.AppendLine() - Console.WriteLine(sb.ToString()) - End Sub + Public Sub Main() + Dim sb As New StringBuilder() + Dim flag As Boolean = True + Dim spellings() As String = {"recieve", "receeve", "receive"} + sb.AppendFormat("Which of the following spellings is {0}:", flag) + sb.AppendLine() + For ctr As Integer = 0 To spellings.GetUpperBound(0) + sb.AppendFormat(" {0}. {1}", ctr, spellings(ctr)) + sb.AppendLine() + Next + sb.AppendLine() + Console.WriteLine(sb.ToString()) + End Sub End Module ' The example displays the following output: ' Which of the following spellings is True: ' 0. recieve ' 1. receeve ' 2. receive -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.Threading.Resuming/vb/Sleep1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.Threading.Resuming/vb/Sleep1.vb index d9bdcf3d7b6a6..6b1ef67a18721 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.Threading.Resuming/vb/Sleep1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.Threading.Resuming/vb/Sleep1.vb @@ -5,42 +5,42 @@ Option Strict On Imports System.Threading Module Example - Public Sub Main() - ' Interrupt a sleeping thread. - Dim sleepingThread = New Thread(AddressOf Example.SleepIndefinitely) - sleepingThread.Name = "Sleeping" - sleepingThread.Start() - Thread.Sleep(2000) - sleepingThread.Interrupt() - - Thread.Sleep(1000) - - sleepingThread = New Thread(AddressOf Example.SleepIndefinitely) - sleepingThread.Name = "Sleeping2" - sleepingThread.Start() - Thread.Sleep(2000) - sleepingThread.Abort() - End Sub + Public Sub Main() + ' Interrupt a sleeping thread. + Dim sleepingThread = New Thread(AddressOf Example.SleepIndefinitely) + sleepingThread.Name = "Sleeping" + sleepingThread.Start() + Thread.Sleep(2000) + sleepingThread.Interrupt() - Private Sub SleepIndefinitely() - Console.WriteLine("Thread '{0}' about to sleep indefinitely.", - Thread.CurrentThread.Name) - Try - Thread.Sleep(Timeout.Infinite) - Catch ex As ThreadInterruptedException - Console.WriteLine("Thread '{0}' awoken.", - Thread.CurrentThread.Name) - Catch ex As ThreadAbortException - Console.WriteLine("Thread '{0}' aborted.", - Thread.CurrentThread.Name) - Finally - Console.WriteLine("Thread '{0}' executing finally block.", - Thread.CurrentThread.Name) - End Try - Console.WriteLine("Thread '{0} finishing normal execution.", - Thread.CurrentThread.Name) - Console.WriteLine() - End Sub + Thread.Sleep(1000) + + sleepingThread = New Thread(AddressOf Example.SleepIndefinitely) + sleepingThread.Name = "Sleeping2" + sleepingThread.Start() + Thread.Sleep(2000) + sleepingThread.Abort() + End Sub + + Private Sub SleepIndefinitely() + Console.WriteLine("Thread '{0}' about to sleep indefinitely.", + Thread.CurrentThread.Name) + Try + Thread.Sleep(Timeout.Infinite) + Catch ex As ThreadInterruptedException + Console.WriteLine("Thread '{0}' awoken.", + Thread.CurrentThread.Name) + Catch ex As ThreadAbortException + Console.WriteLine("Thread '{0}' aborted.", + Thread.CurrentThread.Name) + Finally + Console.WriteLine("Thread '{0}' executing finally block.", + Thread.CurrentThread.Name) + End Try + Console.WriteLine("Thread '{0} finishing normal execution.", + Thread.CurrentThread.Name) + Console.WriteLine() + End Sub End Module ' The example displays the following output: ' Thread 'Sleeping' about to sleep indefinitely. diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/CryptoWalkThru/vb/My Project/AssemblyInfo.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/CryptoWalkThru/vb/My Project/AssemblyInfo.vb index 63e3bc3e55c1b..51b43c5e2229e 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/CryptoWalkThru/vb/My Project/AssemblyInfo.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/CryptoWalkThru/vb/My Project/AssemblyInfo.vb @@ -7,17 +7,17 @@ Imports System.Runtime.InteropServices ' Review the values of the assembly attributes - - - - - - + + + + + + 'The following GUID is for the ID of the typelib if this project is exposed to COM - + ' Version information for an assembly consists of the following four values: ' @@ -30,5 +30,5 @@ Imports System.Runtime.InteropServices ' by using the '*' as shown below: ' - - + + diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/CustomAttributeData/VB/source.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/CustomAttributeData/VB/source.vb index 8ff302b6e0370..131de110957d4 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/CustomAttributeData/VB/source.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/CustomAttributeData/VB/source.vb @@ -4,7 +4,7 @@ Imports System.Collections.Generic Imports System.Collections.ObjectModel ' The example attribute is applied to the assembly. - + ' An enumeration used by the ExampleAttribute class. Public Enum ExampleKind @@ -47,17 +47,17 @@ Public Class ExampleAttribute ' Public ReadOnly Property Kind As ExampleKind Get - Return kindValue + Return kindValue End Get End Property Public ReadOnly Property Strings As String() Get - Return arrayStrings + Return arrayStrings End Get End Property Public Property Note As String Get - Return noteValue + Return noteValue End Get Set noteValue = value @@ -65,7 +65,7 @@ Public Class ExampleAttribute End Property Public Property Numbers As Integer() Get - Return arrayNumbers + Return arrayNumbers End Get Set arrayNumbers = value @@ -76,11 +76,11 @@ End Class ' The example attribute is applied to the test class. ' _ + "String array argument, line 3"}, _ + Note:="This is a note on the class.", _ + Numbers:=New Integer() {53, 57, 59})> _ Public Class Test ' The example attribute is applied to a method, using the ' parameterless constructor and supplying a named argument. @@ -148,7 +148,7 @@ Public Class Test Else Console.WriteLine(" Type: '{0}' Value: '{1}'", _ cata.ArgumentType, cata.Value) - End If + End If End Sub End Class @@ -205,4 +205,4 @@ End Class ' Constructor: 'Void .ctor()' ' Constructor arguments: ' Named arguments: -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/CustomAttributeData/VB/source2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/CustomAttributeData/VB/source2.vb index f6c4cdc7e295f..15a894e9cb81a 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/CustomAttributeData/VB/source2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/CustomAttributeData/VB/source2.vb @@ -18,10 +18,10 @@ Public Class ExampleAttribute End Property End Class - _ + _ Class Class1 Public Shared Sub Main() - Dim info As System.Reflection.MemberInfo = GetType(Class1) + Dim info As System.Reflection.MemberInfo = GetType(Class1) For Each attrib As Object In info.GetCustomAttributes(true) Console.WriteLine(attrib) Next attrib diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb index 0214013b014f7..833d36741783a 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb @@ -8,10 +8,10 @@ Public Class Example ' demonstrate a method bound to an object. ' Private test As Integer - Public Sub New(ByVal test As Integer) - Me.test = test + Public Sub New(ByVal test As Integer) + Me.test = test End Sub - + ' Declare delegates that can be used to execute the completed ' SquareIt dynamic method. The OneParameter delegate can be ' used to execute any method with one parameter and a return @@ -20,16 +20,16 @@ Public Class Example ' ' Private Delegate Function _ - SquareItInvoker(ByVal input As Integer) As Long - + SquareItInvoker(ByVal input As Integer) As Long + ' Private Delegate Function _ OneParameter(Of TReturn, TParameter0) _ - (ByVal p0 As TParameter0) As TReturn + (ByVal p0 As TParameter0) As TReturn ' ' - Public Shared Sub Main() + Public Shared Sub Main() ' Example 1: A simple dynamic method. ' @@ -38,7 +38,7 @@ Public Class Example ' Integer, so the array has only one element. ' ' - Dim methodArgs As Type() = { GetType(Integer) } + Dim methodArgs As Type() = {GetType(Integer)} ' ' Create a DynamicMethod. In this example the method is @@ -96,8 +96,8 @@ Public Class Example GetType(OneParameter(Of Long, Integer))), _ OneParameter(Of Long, Integer) _ ) - - Console.WriteLine("123456789 squared = {0}", _ + + Console.WriteLine("123456789 squared = {0}", _ invokeSquareIt(123456789)) ' @@ -112,7 +112,7 @@ Public Class Example ' ' Dim methodArgs2 As Type() = _ - { GetType(Example), GetType(Integer) } + {GetType(Example), GetType(Integer)} ' ' Create a DynamicMethod. In this example the method has no @@ -144,7 +144,7 @@ Public Class Example ' Dim ilMP As ILGenerator = multiplyPrivate.GetILGenerator() ilMP.Emit(OpCodes.Ldarg_0) - + Dim testInfo As FieldInfo = _ GetType(Example).GetField("test", _ BindingFlags.NonPublic Or BindingFlags.Instance) @@ -179,11 +179,11 @@ Public Class Example ), _ OneParameter(Of Integer, Integer) _ ) - + Console.WriteLine("3 * test = {0}", invoke(3)) ' - End Sub + End Sub End Class @@ -192,4 +192,4 @@ End Class '123456789 squared = 15241578750190521 '3 * test = 126 ' -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb index b6d14b9afe147..4bd47d3d30b43 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb @@ -53,7 +53,7 @@ Public Class Example Dim baseType As Type = GetType(ExampleBase) Dim interfaceA As Type = GetType(IExampleA) Dim interfaceB As Type = GetType(IExampleB) - + ' Define the sample type. ' ' @@ -126,7 +126,7 @@ Public Class Example ' Dim listOf As Type = GetType(List(Of )) Dim listOfTFirst As Type = listOf.MakeGenericType(TFirst) - Dim mParamTypes() As Type = { TFirst.MakeArrayType() } + Dim mParamTypes() As Type = {TFirst.MakeArrayType()} Dim exMethod As MethodBuilder = _ myType.DefineMethod("ExampleMethod", _ @@ -172,12 +172,12 @@ Public Class Example ' ' Dim ilgen As ILGenerator = exMethod.GetILGenerator() - + Dim ienumOf As Type = GetType(IEnumerable(Of )) Dim listOfTParams() As Type = listOf.GetGenericArguments() Dim TfromListOf As Type = listOfTParams(0) Dim ienumOfT As Type = ienumOf.MakeGenericType(TfromListOf) - Dim ctorArgs() As Type = { ienumOfT } + Dim ctorArgs() As Type = {ienumOfT} Dim ctorPrep As ConstructorInfo = _ listOf.GetConstructor(ctorArgs) @@ -208,7 +208,7 @@ Public Class Example ' ' Dim typeArgs() As Type = _ - { GetType(Example), GetType(ExampleDerived) } + {GetType(Example), GetType(ExampleDerived)} Dim constructed As Type = finished.MakeGenericType(typeArgs) Dim mi As MethodInfo = constructed.GetMethod("ExampleMethod") ' @@ -220,14 +220,14 @@ Public Class Example ' on the resulting List(Of Example). ' ' - Dim input() As Example = { New Example(), New Example() } - Dim arguments() As Object = { input } + Dim input() As Example = {New Example(), New Example()} + Dim arguments() As Object = {input} Dim listX As List(Of Example) = mi.Invoke(Nothing, arguments) Console.WriteLine(vbLf & _ "There are {0} elements in the List(Of Example).", _ - listX.Count _ + listX.Count _ ) ' @@ -259,7 +259,7 @@ Public Class Example Else Console.WriteLine(" Base type constraint: {0}", c) End If - Next + Next ListConstraintAttributes(tParam) Next tParam @@ -288,7 +288,7 @@ Public Class Example <> GenericParameterAttributes.None Then _ Console.WriteLine(" DefaultConstructorConstraint") - End Sub + End Sub End Class @@ -309,4 +309,4 @@ End Class ' Interface constraint: IExampleA ' Interface constraint: IExampleB ' Base type constraint: ExampleBase -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Exception.Throwing/VB/throw.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Exception.Throwing/VB/throw.vb index 27b3356d50d41..cb4bc2036b25b 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Exception.Throwing/VB/throw.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Exception.Throwing/VB/throw.vb @@ -6,23 +6,23 @@ Option Strict On Imports System.IO Public Class ProcessFile - - Public Shared Sub Main() - Dim fs As FileStream - Try - ' Opens a text file. - fs = New FileStream("c:\temp\data.txt", FileMode.Open) - Dim sr As New StreamReader(fs) - ' A value is read from the file and output to the console. - Dim line As String = sr.ReadLine() - Console.WriteLine(line) - Catch e As FileNotFoundException - Console.WriteLine($"[Data File Missing] {e}") - Throw New FileNotFoundException("[data.txt not in c:\temp directory]", e) - Finally - If fs IsNot Nothing Then fs.Close() - End Try - End Sub -End Class + Public Shared Sub Main() + Dim fs As FileStream + Try + ' Opens a text file. + fs = New FileStream("c:\temp\data.txt", FileMode.Open) + Dim sr As New StreamReader(fs) + + ' A value is read from the file and output to the console. + Dim line As String = sr.ReadLine() + Console.WriteLine(line) + Catch e As FileNotFoundException + Console.WriteLine($"[Data File Missing] {e}") + Throw New FileNotFoundException("[data.txt not in c:\temp directory]", e) + Finally + If fs IsNot Nothing Then fs.Close() + End Try + End Sub +End Class ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/Composite1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/Composite1.vb index 68a4cfbeb5b8c..0ccf059e6dbf8 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/Composite1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/Composite1.vb @@ -2,72 +2,72 @@ Option Strict On Module modMain - Public Sub Main() - ' - Dim name As String = "Fred" - ' - String.Format("Name = {0}, hours = {1:hh}", name, DateTime.Now) - ' - ' + Public Sub Main() + ' + Dim name As String = "Fred" + ' + String.Format("Name = {0}, hours = {1:hh}", name, DateTime.Now) + ' + ' - ' - Dim FormatString1 As String = String.Format("{0:dddd MMMM}", DateTime.Now) - Dim FormatString2 As String = DateTime.Now.ToString("dddd MMMM") - ' - - ' - Dim MyInt As Integer = 100 - Console.WriteLine("{0:C}", MyInt) - ' The example displays the following output - ' if en-US is the current culture: - ' $100.00 - ' - - CallSnippet5() - Console.WriteLine() - CallSnippet6() - End Sub - - Private Sub CallSnippet5() - ' - Dim myName As String = "Fred" - Console.WriteLine(String.Format("Name = {0}, hours = {1:hh}, minutes = {1:mm}", _ - myName, DateTime.Now)) - ' Depending on the current time, the example displays output like the following: - ' Name = Fred, hours = 11, minutes = 30 - ' - End Sub - - Private Sub CallSnippet6 - ' - Dim myFName As String = "Fred" - Dim myLName As String = "Opals" - - Dim myInt As Integer = 100 - Dim FormatFName As String = String.Format("First Name = |{0,10}|", myFName) - Dim FormatLName As String = String.Format("Last Name = |{0,10}|", myLName) - Dim FormatPrice As String = String.Format("Price = |{0,10:C}|", myInt) - Console.WriteLine(FormatFName) - Console.WriteLine(FormatLName) - Console.WriteLine(FormatPrice) - Console.WriteLine() - - FormatFName = String.Format("First Name = |{0,-10}|", myFName) - FormatLName = String.Format("Last Name = |{0,-10}|", myLName) - FormatPrice = String.Format("Price = |{0,-10:C}|", myInt) - Console.WriteLine(FormatFName) - Console.WriteLine(FormatLName) - Console.WriteLine(FormatPrice) - ' The example displays the following output on a system whose current - ' culture is en-US: - ' First Name = | Fred| - ' Last Name = | Opals| - ' Price = | $100.00| - ' - ' First Name = |Fred | - ' Last Name = |Opals | - ' Price = |$100.00 | - ' - End Sub + ' + Dim FormatString1 As String = String.Format("{0:dddd MMMM}", DateTime.Now) + Dim FormatString2 As String = DateTime.Now.ToString("dddd MMMM") + ' + + ' + Dim MyInt As Integer = 100 + Console.WriteLine("{0:C}", MyInt) + ' The example displays the following output + ' if en-US is the current culture: + ' $100.00 + ' + + CallSnippet5() + Console.WriteLine() + CallSnippet6() + End Sub + + Private Sub CallSnippet5() + ' + Dim myName As String = "Fred" + Console.WriteLine(String.Format("Name = {0}, hours = {1:hh}, minutes = {1:mm}", _ + myName, DateTime.Now)) + ' Depending on the current time, the example displays output like the following: + ' Name = Fred, hours = 11, minutes = 30 + ' + End Sub + + Private Sub CallSnippet6 + ' + Dim myFName As String = "Fred" + Dim myLName As String = "Opals" + + Dim myInt As Integer = 100 + Dim FormatFName As String = String.Format("First Name = |{0,10}|", myFName) + Dim FormatLName As String = String.Format("Last Name = |{0,10}|", myLName) + Dim FormatPrice As String = String.Format("Price = |{0,10:C}|", myInt) + Console.WriteLine(FormatFName) + Console.WriteLine(FormatLName) + Console.WriteLine(FormatPrice) + Console.WriteLine() + + FormatFName = String.Format("First Name = |{0,-10}|", myFName) + FormatLName = String.Format("Last Name = |{0,-10}|", myLName) + FormatPrice = String.Format("Price = |{0,-10:C}|", myInt) + Console.WriteLine(FormatFName) + Console.WriteLine(FormatLName) + Console.WriteLine(FormatPrice) + ' The example displays the following output on a system whose current + ' culture is en-US: + ' First Name = | Fred| + ' Last Name = | Opals| + ' Price = | $100.00| + ' + ' First Name = |Fred | + ' Last Name = |Opals | + ' Price = |$100.00 | + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/Escaping1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/Escaping1.vb index 1eb870ac59c84..3b0fa9871c84e 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/Escaping1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/Escaping1.vb @@ -4,15 +4,15 @@ Option Strict On Module modMain - Public Sub Main() - ' - Dim value As Integer = 6324 - Dim output As String = String.Format("{0}{1:D}{2}", _ - "{", value, "}") - Console.WriteLine(output) - ' The example displays the following output: - ' {6324} - ' - End Sub + Public Sub Main() + ' + Dim value As Integer = 6324 + Dim output As String = String.Format("{0}{1:D}{2}", _ + "{", value, "}") + Console.WriteLine(output) + ' The example displays the following output: + ' {6324} + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/alignment1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/alignment1.vb index 20122befad9b7..0ded2073fddcb 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/alignment1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/alignment1.vb @@ -3,18 +3,18 @@ Option Strict On ' Module Example - Public Sub Main() - Dim names() As String = { "Adam", "Bridgette", "Carla", "Daniel", - "Ebenezer", "Francine", "George" } - Dim hours() As Decimal = { 40, 6.667d, 40.39d, 82, 40.333d, 80, - 16.75d } + Public Sub Main() + Dim names() As String = {"Adam", "Bridgette", "Carla", "Daniel", + "Ebenezer", "Francine", "George"} + Dim hours() As Decimal = {40, 6.667d, 40.39d, 82, 40.333d, 80, + 16.75d} - Console.WriteLine("{0,-20} {1,5}", "Name", "Hours") - Console.WriteLine() - For ctr As Integer = 0 To names.Length - 1 - Console.WriteLine("{0,-20} {1,5:N1}", names(ctr), hours(ctr)) - Next - End Sub + Console.WriteLine("{0,-20} {1,5}", "Name", "Hours") + Console.WriteLine() + For ctr As Integer = 0 To names.Length - 1 + Console.WriteLine("{0,-20} {1,5:N1}", names(ctr), hours(ctr)) + Next + End Sub End Module ' The example displays the following output: ' Name Hours diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/index1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/index1.vb index 91cb2ed3b0430..519776bb380c6 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/index1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Composite/vb/index1.vb @@ -2,26 +2,26 @@ Option Strict On Module Example - Public Sub Main() + Public Sub Main() - ' - Dim primes As String - primes = String.Format("Prime numbers less than 10: {0}, {1}, {2}, {3}", - 2, 3, 5, 7 ) - Console.WriteLine(primes) - ' The example displays the following output: - ' Prime numbers less than 10: 2, 3, 5, 7 - ' - Console.WriteLine() + ' + Dim primes As String + primes = String.Format("Prime numbers less than 10: {0}, {1}, {2}, {3}", + 2, 3, 5, 7) + Console.WriteLine(primes) + ' The example displays the following output: + ' Prime numbers less than 10: 2, 3, 5, 7 + ' + Console.WriteLine() - ' - Dim multiple As String = String.Format("0x{0:X} {0:E} {0:N}", - Int64.MaxValue) - Console.WriteLine(multiple) - ' The example displays the following output: - ' 0x7FFFFFFFFFFFFFFF 9.223372E+018 9,223,372,036,854,775,807.00 - ' - Console.WriteLine() - End Sub + ' + Dim multiple As String = String.Format("0x{0:X} {0:E} {0:N}", + Int64.MaxValue) + Console.WriteLine(multiple) + ' The example displays the following output: + ' 0x7FFFFFFFFFFFFFFF 9.223372E+018 9,223,372,036,854,775,807.00 + ' + Console.WriteLine() + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/Custom1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/Custom1.vb index 5d4918f1a821f..7bd38003ed2fc 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/Custom1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/Custom1.vb @@ -4,274 +4,274 @@ Option Strict On Imports System.Globalization Module modMain - Public Sub Main() - Show_dSpecifier() - Console.WriteLine() - Show_ddSpecifier() - Show_dddSpecifier() - Show_ddddSpecifier() - Show_fSpecifiers() - Show_gSpecifier() - Show_hSpecifier() - Show_hhSpecifier() - ShowHSpecifier() - ShowHHSpecifier() - ShowMSpecifier() - ShowKSpecifier() - Show_ySpecifier() - Show_zSpecifier() - End Sub - - Private Sub Show_dSpecifier() - Console.WriteLine("d format specifier") - ' - Dim date1 As Date = #08/29/2008 7:27:15PM# - - Console.WriteLine(date1.ToString("d, M", _ - CultureInfo.InvariantCulture)) - ' Displays 29, 8 - - Console.WriteLine(date1.ToString("d MMMM", _ - CultureInfo.CreateSpecificCulture("en-US"))) - ' Displays 29 August - Console.WriteLine(date1.ToString("d MMMM", _ - CultureInfo.CreateSpecificCulture("es-MX"))) - ' Displays 29 agosto - ' - Console.WriteLine() - End Sub - - Private Sub Show_ddSpecifier() - Console.WriteLine("dd format specifier") - ' - Dim date1 As Date = #1/2/2008 6:30:15AM# - - Console.WriteLine(date1.ToString("dd, MM", _ - CultureInfo.InvariantCulture)) - ' 02, 01 - ' - Console.WriteLine() - End Sub - - Private Sub Show_dddSpecifier() - Console.WriteLine("ddd format specifier") - ' - Dim date1 As Date = #08/29/2008 7:27:15PM# - - Console.WriteLine(date1.ToString("ddd d MMM", _ - CultureInfo.CreateSpecificCulture("en-US"))) - ' Displays Fri 29 Aug - Console.WriteLine(date1.ToString("ddd d MMM", _ - CultureInfo.CreateSpecificCulture("fr-FR"))) - ' Displays ven. 29 août - ' - Console.WriteLine() - End Sub - - Private Sub Show_ddddSpecifier() - Console.WriteLine("dddd format specifier") - ' - Dim date1 As Date = #08/29/2008 7:27:15PM# - - Console.WriteLine(date1.ToString("dddd dd MMMM", _ - CultureInfo.CreateSpecificCulture("en-US"))) - ' Displays Friday 29 August - Console.WriteLine(date1.ToString("dddd dd MMMM", _ - CultureInfo.CreateSpecificCulture("it-IT"))) - ' Displays venerdì 29 agosto - ' - Console.WriteLine() - End Sub - - Private Sub Show_fSpecifiers() - Console.WriteLine("f and F format specifiers") - ' - Dim date1 As New Date(2008, 8, 29, 19, 27, 15, 018) - Dim ci As CultureInfo = CultureInfo.InvariantCulture + Public Sub Main() + Show_dSpecifier() + Console.WriteLine() + Show_ddSpecifier() + Show_dddSpecifier() + Show_ddddSpecifier() + Show_fSpecifiers() + Show_gSpecifier() + Show_hSpecifier() + Show_hhSpecifier() + ShowHSpecifier() + ShowHHSpecifier() + ShowMSpecifier() + ShowKSpecifier() + Show_ySpecifier() + Show_zSpecifier() + End Sub + + Private Sub Show_dSpecifier() + Console.WriteLine("d format specifier") + ' + Dim date1 As Date = #08/29/2008 7:27:15PM# + + Console.WriteLine(date1.ToString("d, M", _ + CultureInfo.InvariantCulture)) + ' Displays 29, 8 + + Console.WriteLine(date1.ToString("d MMMM", _ + CultureInfo.CreateSpecificCulture("en-US"))) + ' Displays 29 August + Console.WriteLine(date1.ToString("d MMMM", _ + CultureInfo.CreateSpecificCulture("es-MX"))) + ' Displays 29 agosto + ' + Console.WriteLine() + End Sub + + Private Sub Show_ddSpecifier() + Console.WriteLine("dd format specifier") + ' + Dim date1 As Date = #1/2/2008 6:30:15AM# + + Console.WriteLine(date1.ToString("dd, MM", _ + CultureInfo.InvariantCulture)) + ' 02, 01 + ' + Console.WriteLine() + End Sub - Console.WriteLine(date1.ToString("hh:mm:ss.f", ci)) - ' Displays 07:27:15.0 - Console.WriteLine(date1.ToString("hh:mm:ss.F", ci)) - ' Displays 07:27:15 - Console.WriteLine(date1.ToString("hh:mm:ss.ff", ci)) - ' Displays 07:27:15.01 - Console.WriteLine(date1.ToString("hh:mm:ss.FF", ci)) - ' Displays 07:27:15.01 - Console.WriteLine(date1.ToString("hh:mm:ss.fff", ci)) - ' Displays 07:27:15.018 - Console.WriteLine(date1.ToString("hh:mm:ss.FFF", ci)) - ' Displays 07:27:15.018 - ' - Console.WriteLine() - End Sub + Private Sub Show_dddSpecifier() + Console.WriteLine("ddd format specifier") + ' + Dim date1 As Date = #08/29/2008 7:27:15PM# - Private Sub Show_gSpecifier() - Console.WriteLine("g format specifier") - ' - Dim date1 As Date = #08/04/0070# - - Console.WriteLine(date1.ToString("MM/dd/yyyy g", _ - CultureInfo.InvariantCulture)) - ' Displays 08/04/0070 A.D. - Console.WriteLine(date1.ToString("MM/dd/yyyy g", _ - CultureInfo.CreateSpecificCulture("fr-FR"))) - ' Displays 08/04/0070 ap. J.-C. - ' - Console.WriteLine() + Console.WriteLine(date1.ToString("ddd d MMM", _ + CultureInfo.CreateSpecificCulture("en-US"))) + ' Displays Fri 29 Aug + Console.WriteLine(date1.ToString("ddd d MMM", _ + CultureInfo.CreateSpecificCulture("fr-FR"))) + ' Displays ven. 29 août + ' + Console.WriteLine() End Sub - + + Private Sub Show_ddddSpecifier() + Console.WriteLine("dddd format specifier") + ' + Dim date1 As Date = #08/29/2008 7:27:15PM# + + Console.WriteLine(date1.ToString("dddd dd MMMM", _ + CultureInfo.CreateSpecificCulture("en-US"))) + ' Displays Friday 29 August + Console.WriteLine(date1.ToString("dddd dd MMMM", _ + CultureInfo.CreateSpecificCulture("it-IT"))) + ' Displays venerdì 29 agosto + ' + Console.WriteLine() + End Sub + + Private Sub Show_fSpecifiers() + Console.WriteLine("f and F format specifiers") + ' + Dim date1 As New Date(2008, 8, 29, 19, 27, 15, 018) + Dim ci As CultureInfo = CultureInfo.InvariantCulture + + Console.WriteLine(date1.ToString("hh:mm:ss.f", ci)) + ' Displays 07:27:15.0 + Console.WriteLine(date1.ToString("hh:mm:ss.F", ci)) + ' Displays 07:27:15 + Console.WriteLine(date1.ToString("hh:mm:ss.ff", ci)) + ' Displays 07:27:15.01 + Console.WriteLine(date1.ToString("hh:mm:ss.FF", ci)) + ' Displays 07:27:15.01 + Console.WriteLine(date1.ToString("hh:mm:ss.fff", ci)) + ' Displays 07:27:15.018 + Console.WriteLine(date1.ToString("hh:mm:ss.FFF", ci)) + ' Displays 07:27:15.018 + ' + Console.WriteLine() + End Sub + + Private Sub Show_gSpecifier() + Console.WriteLine("g format specifier") + ' + Dim date1 As Date = #08/04/0070# + + Console.WriteLine(date1.ToString("MM/dd/yyyy g", _ + CultureInfo.InvariantCulture)) + ' Displays 08/04/0070 A.D. + Console.WriteLine(date1.ToString("MM/dd/yyyy g", _ + CultureInfo.CreateSpecificCulture("fr-FR"))) + ' Displays 08/04/0070 ap. J.-C. + ' + Console.WriteLine() + End Sub + Private Sub Show_hSpecifier() - Console.WriteLine("h format specifier") - ' - Dim date1 As Date - date1 = #6:09:01PM# - Console.WriteLine(date1.ToString("h:m:s.F t", _ - CultureInfo.InvariantCulture)) - ' Displays 6:9:1 P - Console.WriteLine(date1.ToString("h:m:s.F t", _ - CultureInfo.CreateSpecificCulture("el-GR"))) - ' Displays 6:9:1 µ - date1 = New Date(2008, 1, 1, 18, 9, 1, 500) - Console.WriteLine(date1.ToString("h:m:s.F t", _ - CultureInfo.InvariantCulture)) - ' Displays 6:9:1.5 P - Console.WriteLine(date1.ToString("h:m:s.F t", _ - CultureInfo.CreateSpecificCulture("el-GR"))) - ' Displays 6:9:1.5 µ - ' - Console.WriteLine() + Console.WriteLine("h format specifier") + ' + Dim date1 As Date + date1 = #6:09:01PM# + Console.WriteLine(date1.ToString("h:m:s.F t", _ + CultureInfo.InvariantCulture)) + ' Displays 6:9:1 P + Console.WriteLine(date1.ToString("h:m:s.F t", _ + CultureInfo.CreateSpecificCulture("el-GR"))) + ' Displays 6:9:1 µ + date1 = New Date(2008, 1, 1, 18, 9, 1, 500) + Console.WriteLine(date1.ToString("h:m:s.F t", _ + CultureInfo.InvariantCulture)) + ' Displays 6:9:1.5 P + Console.WriteLine(date1.ToString("h:m:s.F t", _ + CultureInfo.CreateSpecificCulture("el-GR"))) + ' Displays 6:9:1.5 µ + ' + Console.WriteLine() End Sub - + Private Sub Show_hhSpecifier() - Console.WriteLine("hh format specifier") - ' - Dim date1 As Date - date1 = #6:09:01PM# - Console.WriteLine(date1.ToString("hh:mm:ss tt", _ - CultureInfo.InvariantCulture)) - ' Displays 06:09:01 PM - Console.WriteLine(date1.ToString("hh:mm:ss tt", _ - CultureInfo.CreateSpecificCulture("hu-HU"))) - ' Displays 06:09:01 du. - date1 = New Date(2008, 1, 1, 18, 9, 1, 500) - Console.WriteLine(date1.ToString("hh:mm:ss.ff tt", _ - CultureInfo.InvariantCulture)) - ' Displays 06:09:01.50 PM - Console.WriteLine(date1.ToString("hh:mm:ss.ff tt", _ - CultureInfo.CreateSpecificCulture("hu-HU"))) - ' Displays 06:09:01.50 du. - ' - Console.WriteLine() - End Sub - - Private Sub ShowHSpecifier() - Console.WriteLine("H format specifier") - ' - Dim date1 As Date = #6:09:01AM# - Console.WriteLine(date1.ToString("H:mm:ss", _ - CultureInfo.InvariantCulture)) - ' Displays 6:09:01 - ' - Console.WriteLine() - End Sub - - Private Sub ShowHHSpecifier() - Console.WriteLine("HH format specifier") - ' - Dim date1 As Date = #6:09:01AM# - Console.WriteLine(date1.ToString("HH:mm:ss", _ - CultureInfo.InvariantCulture)) - ' Displays 06:09:01 - ' - Console.WriteLine() - End Sub - - Private Sub ShowMSpecifier() - Console.WriteLine("M format specifier") - ' - Dim date1 As Date = #8/18/2008# - Console.WriteLine(date1.ToString("(M) MMM, MMMM", _ - CultureInfo.CreateSpecificCulture("en-US"))) - ' Displays (8) Aug, August - Console.WriteLine(date1.ToString("(M) MMM, MMMM", _ - CultureInfo.CreateSpecificCulture("nl-NL"))) - ' Displays (8) aug, augustus - Console.WriteLine(date1.ToString("(M) MMM, MMMM", _ - CultureInfo.CreateSpecificCulture("lv-LV"))) - ' Displays (8) Aug, augusts - ' - Console.WriteLine() - End Sub + Console.WriteLine("hh format specifier") + ' + Dim date1 As Date + date1 = #6:09:01PM# + Console.WriteLine(date1.ToString("hh:mm:ss tt", _ + CultureInfo.InvariantCulture)) + ' Displays 06:09:01 PM + Console.WriteLine(date1.ToString("hh:mm:ss tt", _ + CultureInfo.CreateSpecificCulture("hu-HU"))) + ' Displays 06:09:01 du. + date1 = New Date(2008, 1, 1, 18, 9, 1, 500) + Console.WriteLine(date1.ToString("hh:mm:ss.ff tt", _ + CultureInfo.InvariantCulture)) + ' Displays 06:09:01.50 PM + Console.WriteLine(date1.ToString("hh:mm:ss.ff tt", _ + CultureInfo.CreateSpecificCulture("hu-HU"))) + ' Displays 06:09:01.50 du. + ' + Console.WriteLine() + End Sub - Private Sub ShowKSpecifier() - Console.WriteLine("K format specifier") - ' - Console.WriteLine(Date.Now.ToString("%K")) - ' Displays -07:00 - Console.WriteLine(Date.UtcNow.ToString("%K")) - ' Displays Z - Console.WriteLine("'{0}'", _ - Date.SpecifyKind(Date.Now, _ - DateTimeKind.Unspecified). _ - ToString("%K")) - ' Displays '' - Console.WriteLine(DateTimeOffset.Now.ToString("%K")) - ' Displays -07:00 - Console.WriteLine(DateTimeOffset.UtcNow.ToString("%K")) - ' Displays +00:00 - Console.WriteLine(New DateTimeOffset(2008, 5, 1, 6, 30, 0, _ - New TimeSpan(5, 0, 0)). _ - ToString("%K")) - ' Displays +05:00 - ' - Console.WriteLine() - End Sub - - Private Sub Show_ySpecifier() - Console.WriteLine("y format specifier") - ' - Dim date1 As Date = #12/1/0001# - Dim date2 As Date = #1/1/2010# - Console.WriteLine(date1.ToString("%y")) - ' Displays 1 - Console.WriteLine(date1.ToString("yy")) - ' Displays 01 - Console.WriteLine(date1.ToString("yyy")) - ' Displays 001 - Console.WriteLine(date1.ToString("yyyy")) - ' Displays 0001 - Console.WriteLine(date1.ToString("yyyyy")) - ' Displays 00001 - Console.WriteLine(date2.ToString("%y")) - ' Displays 10 - Console.WriteLine(date2.ToString("yy")) - ' Displays 10 - Console.WriteLine(date2.ToString("yyy")) - ' Displays 2010 - Console.WriteLine(date2.ToString("yyyy")) - ' Displays 2010 - Console.WriteLine(date2.ToString("yyyyy")) - ' Displays 02010 - ' - Console.WriteLine() - End Sub - - Private Sub Show_zSpecifier() - Console.WriteLine("z format specifier") - ' - Dim date1 As Date = Date.UtcNow - Console.WriteLine(String.Format("{0:%z}, {0:zz}, {0:zzz}", _ - date1)) - ' Displays -7, -07, -07:00 + Private Sub ShowHSpecifier() + Console.WriteLine("H format specifier") + ' + Dim date1 As Date = #6:09:01AM# + Console.WriteLine(date1.ToString("H:mm:ss", _ + CultureInfo.InvariantCulture)) + ' Displays 6:09:01 + ' + Console.WriteLine() + End Sub + + Private Sub ShowHHSpecifier() + Console.WriteLine("HH format specifier") + ' + Dim date1 As Date = #6:09:01AM# + Console.WriteLine(date1.ToString("HH:mm:ss", _ + CultureInfo.InvariantCulture)) + ' Displays 06:09:01 + ' + Console.WriteLine() + End Sub - Dim date2 As New DateTimeOffset(2008, 8, 1, 0, 0, 0, _ - New Timespan(6, 0, 0)) - Console.WriteLine(String.Format("{0:%z}, {0:zz}, {0:zzz}", _ - date2)) - ' Displays +6, +06, +06:00 - ' - Console.WriteLine() - End Sub + Private Sub ShowMSpecifier() + Console.WriteLine("M format specifier") + ' + Dim date1 As Date = #8/18/2008# + Console.WriteLine(date1.ToString("(M) MMM, MMMM", _ + CultureInfo.CreateSpecificCulture("en-US"))) + ' Displays (8) Aug, August + Console.WriteLine(date1.ToString("(M) MMM, MMMM", _ + CultureInfo.CreateSpecificCulture("nl-NL"))) + ' Displays (8) aug, augustus + Console.WriteLine(date1.ToString("(M) MMM, MMMM", _ + CultureInfo.CreateSpecificCulture("lv-LV"))) + ' Displays (8) Aug, augusts + ' + Console.WriteLine() + End Sub + + Private Sub ShowKSpecifier() + Console.WriteLine("K format specifier") + ' + Console.WriteLine(Date.Now.ToString("%K")) + ' Displays -07:00 + Console.WriteLine(Date.UtcNow.ToString("%K")) + ' Displays Z + Console.WriteLine("'{0}'", _ + Date.SpecifyKind(Date.Now, _ + DateTimeKind.Unspecified). _ + ToString("%K")) + ' Displays '' + Console.WriteLine(DateTimeOffset.Now.ToString("%K")) + ' Displays -07:00 + Console.WriteLine(DateTimeOffset.UtcNow.ToString("%K")) + ' Displays +00:00 + Console.WriteLine(New DateTimeOffset(2008, 5, 1, 6, 30, 0, _ + New TimeSpan(5, 0, 0)). _ + ToString("%K")) + ' Displays +05:00 + ' + Console.WriteLine() + End Sub + + Private Sub Show_ySpecifier() + Console.WriteLine("y format specifier") + ' + Dim date1 As Date = #12/1/0001# + Dim date2 As Date = #1/1/2010# + Console.WriteLine(date1.ToString("%y")) + ' Displays 1 + Console.WriteLine(date1.ToString("yy")) + ' Displays 01 + Console.WriteLine(date1.ToString("yyy")) + ' Displays 001 + Console.WriteLine(date1.ToString("yyyy")) + ' Displays 0001 + Console.WriteLine(date1.ToString("yyyyy")) + ' Displays 00001 + Console.WriteLine(date2.ToString("%y")) + ' Displays 10 + Console.WriteLine(date2.ToString("yy")) + ' Displays 10 + Console.WriteLine(date2.ToString("yyy")) + ' Displays 2010 + Console.WriteLine(date2.ToString("yyyy")) + ' Displays 2010 + Console.WriteLine(date2.ToString("yyyyy")) + ' Displays 02010 + ' + Console.WriteLine() + End Sub + + Private Sub Show_zSpecifier() + Console.WriteLine("z format specifier") + ' + Dim date1 As Date = Date.UtcNow + Console.WriteLine(String.Format("{0:%z}, {0:zz}, {0:zzz}", _ + date1)) + ' Displays -7, -07, -07:00 + + Dim date2 As New DateTimeOffset(2008, 8, 1, 0, 0, 0, _ + New Timespan(6, 0, 0)) + Console.WriteLine(String.Format("{0:%z}, {0:zz}, {0:zzz}", _ + date2)) + ' Displays +6, +06, +06:00 + ' + Console.WriteLine() + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/LiteralsEx1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/LiteralsEx1.vb index 5c121e9e62e15..d904f4e6bfdd2 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/LiteralsEx1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/LiteralsEx1.vb @@ -5,23 +5,23 @@ Option Strict On Imports System.Globalization Module Example - Public Sub Main() - Dim formats() As String = { "dd MMM yyyy hh:mm tt PST", - "dd MMM yyyy hh:mm tt PDT" } - Dim dat As New Date(2016, 8, 18, 16, 50, 0) - ' Display the result string. - Console.WriteLine(dat.ToString(formats(1))) - - ' Parse a string. - Dim value As String = "25 Dec 2016 12:00 pm PST" - Dim newDate As Date - If Date.TryParseExact(value, formats, Nothing, - DateTimeStyles.None, newDate) Then - Console.WriteLine(newDate) - Else - Console.WriteLine("Unable to parse '{0}'", value) - End If - End Sub + Public Sub Main() + Dim formats() As String = {"dd MMM yyyy hh:mm tt PST", + "dd MMM yyyy hh:mm tt PDT"} + Dim dat As New Date(2016, 8, 18, 16, 50, 0) + ' Display the result string. + Console.WriteLine(dat.ToString(formats(1))) + + ' Parse a string. + Dim value As String = "25 Dec 2016 12:00 pm PST" + Dim newDate As Date + If Date.TryParseExact(value, formats, Nothing, + DateTimeStyles.None, newDate) Then + Console.WriteLine(newDate) + Else + Console.WriteLine("Unable to parse '{0}'", value) + End If + End Sub End Module ' The example displays the following output: ' 18 Aug 2016 04:50 PM PDT diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/LiteralsEx2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/LiteralsEx2.vb index 744bbef85798b..de448ac107654 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/LiteralsEx2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/LiteralsEx2.vb @@ -5,22 +5,22 @@ Option Strict On Imports System.Globalization Module Example - Public Sub Main() - Dim fmt As String = "dd MMM yyyy hh:mm tt p\s\t" - Dim dat As New Date(2016, 8, 18, 16, 50, 0) - ' Display the result string. - Console.WriteLine(dat.ToString(fmt)) - - ' Parse a string. - Dim value As String = "25 Dec 2016 12:00 pm pst" - Dim newDate As Date - If Date.TryParseExact(value, fmt, Nothing, - DateTimeStyles.None, newDate) Then - Console.WriteLine(newDate) - Else - Console.WriteLine("Unable to parse '{0}'", value) - End If - End Sub + Public Sub Main() + Dim fmt As String = "dd MMM yyyy hh:mm tt p\s\t" + Dim dat As New Date(2016, 8, 18, 16, 50, 0) + ' Display the result string. + Console.WriteLine(dat.ToString(fmt)) + + ' Parse a string. + Dim value As String = "25 Dec 2016 12:00 pm pst" + Dim newDate As Date + If Date.TryParseExact(value, fmt, Nothing, + DateTimeStyles.None, newDate) Then + Console.WriteLine(newDate) + Else + Console.WriteLine("Unable to parse '{0}'", value) + End If + End Sub End Module ' The example displays the following output: ' 18 Aug 2016 04:50 PM pst diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/LiteralsEx3.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/LiteralsEx3.vb index eed12c4089bcd..28099c0c9cdf5 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/LiteralsEx3.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/LiteralsEx3.vb @@ -5,22 +5,22 @@ Option Strict On Imports System.Globalization Module Example - Public Sub Main() - Dim fmt As String = "dd MMM yyyy hh:mm tt ""pst""" - Dim dat As New Date(2016, 8, 18, 16, 50, 0) - ' Display the result string. - Console.WriteLine(dat.ToString(fmt)) - - ' Parse a string. - Dim value As String = "25 Dec 2016 12:00 pm pst" - Dim newDate As Date - If Date.TryParseExact(value, fmt, Nothing, - DateTimeStyles.None, newDate) Then - Console.WriteLine(newDate) - Else - Console.WriteLine("Unable to parse '{0}'", value) - End If - End Sub + Public Sub Main() + Dim fmt As String = "dd MMM yyyy hh:mm tt ""pst""" + Dim dat As New Date(2016, 8, 18, 16, 50, 0) + ' Display the result string. + Console.WriteLine(dat.ToString(fmt)) + + ' Parse a string. + Dim value As String = "25 Dec 2016 12:00 pm pst" + Dim newDate As Date + If Date.TryParseExact(value, fmt, Nothing, + DateTimeStyles.None, newDate) Then + Console.WriteLine(newDate) + Else + Console.WriteLine("Unable to parse '{0}'", value) + End If + End Sub End Module ' The example displays the following output: ' 18 Aug 2016 04:50 PM pst diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/custandformatting1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/custandformatting1.vb index a72b86ffcb781..38deb4c58f884 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/custandformatting1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/custandformatting1.vb @@ -2,18 +2,18 @@ Option Strict On Module Example - Public Sub Main() - ' - Dim thisDate1 As Date = #6/10/2011# - Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".") - - Dim thisDate2 As New DateTimeOffset(2011, 6, 10, 15, 24, 16, TimeSpan.Zero) - Console.WriteLine("The current date and time: {0:MM/dd/yy H:mm:ss zzz}", - thisDate2) - ' The example displays the following output: - ' Today is June 10, 2011. - ' The current date and time: 06/10/11 15:24:16 +00:00 - ' - End Sub + Public Sub Main() + ' + Dim thisDate1 As Date = #6/10/2011# + Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".") + + Dim thisDate2 As New DateTimeOffset(2011, 6, 10, 15, 24, 16, TimeSpan.Zero) + Console.WriteLine("The current date and time: {0:MM/dd/yy H:mm:ss zzz}", + thisDate2) + ' The example displays the following output: + ' Today is June 10, 2011. + ' The current date and time: 06/10/11 15:24:16 +00:00 + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/custandparsing1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/custandparsing1.vb index 2a18eb64ce098..501f731752596 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/custandparsing1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/custandparsing1.vb @@ -6,23 +6,23 @@ Option Infer On Imports System.Globalization Module Example - Public Sub Main() - Dim dateValues() As String = { "30-12-2011", "12-30-2011", - "30-12-11", "12-30-11" } - Dim pattern As String = "MM-dd-yy" - Dim parsedDate As Date - - For Each dateValue As String In dateValues - If DateTime.TryParseExact(dateValue, pattern, Nothing, - DateTimeStyles.None, parsedDate) Then - Console.WriteLine("Converted '{0}' to {1:d}.", - dateValue, parsedDate) - Else - Console.WriteLine("Unable to convert '{0}' to a date and time.", - dateValue) - End If - Next - End Sub + Public Sub Main() + Dim dateValues() As String = {"30-12-2011", "12-30-2011", + "30-12-11", "12-30-11"} + Dim pattern As String = "MM-dd-yy" + Dim parsedDate As Date + + For Each dateValue As String In dateValues + If DateTime.TryParseExact(dateValue, pattern, Nothing, + DateTimeStyles.None, parsedDate) Then + Console.WriteLine("Converted '{0}' to {1:d}.", + dateValue, parsedDate) + Else + Console.WriteLine("Unable to convert '{0}' to a date and time.", + dateValue) + End If + Next + End Sub End Module ' The example displays the following output: ' Unable to convert '30-12-2011' to a date and time. diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/escape1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/escape1.vb index 8c54900d2abbc..3815c71312dc8 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/escape1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/escape1.vb @@ -2,15 +2,15 @@ Option Strict On Module Example - Public Sub Main() - ' - Dim date1 As Date = #6/15/2009 13:45# - Dim fmt As String = "h \h m \m" + Public Sub Main() + ' + Dim date1 As Date = #6/15/2009 13:45# + Dim fmt As String = "h \h m \m" - Console.WriteLine("{0} ({1}) -> {2}", date1, fmt, date1.ToString(fmt)) - ' The example displays the following output: - ' 6/15/2009 1:45:00 PM (h \h m \m) -> 1 h 45 m - ' - End Sub + Console.WriteLine("{0} ({1}) -> {2}", date1, fmt, date1.ToString(fmt)) + ' The example displays the following output: + ' 6/15/2009 1:45:00 PM (h \h m \m) -> 1 h 45 m + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/literal1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/literal1.vb index 65987ac80aa75..af5e84afefe21 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/literal1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/literal1.vb @@ -2,18 +2,18 @@ Option Strict On Module Example - Public Sub Main() - ' - Dim dat1 As Date = #6/15/2009 1:45PM# - - Console.WriteLine("'{0:%h}'", dat1) - Console.WriteLine("'{0: h}'", dat1) - Console.WriteLine("'{0:h }'", dat1) - ' The example displays the following output: - ' '1' - ' ' 1' - ' '1 ' - ' - End Sub + Public Sub Main() + ' + Dim dat1 As Date = #6/15/2009 1:45PM# + + Console.WriteLine("'{0:%h}'", dat1) + Console.WriteLine("'{0: h}'", dat1) + Console.WriteLine("'{0:h }'", dat1) + ' The example displays the following output: + ' '1' + ' ' 1' + ' '1 ' + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/parseexact2digityear1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/parseexact2digityear1.vb index f7b25b0ea0212..15b7c10d39f78 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/parseexact2digityear1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/parseexact2digityear1.vb @@ -6,26 +6,26 @@ Imports System.Globalization Imports System.Threading Module Example - Public Sub Main() - Dim fmt As String = "dd-MMM-yy" - Dim value As String = "24-Jan-49" - - Dim cal As Calendar = CType(CultureInfo.CurrentCulture.Calendar.Clone(), Calendar) - Console.WriteLine("Two Digit Year Range: {0} - {1}", - cal.TwoDigitYearMax - 99, cal.TwoDigitYearMax) - - Console.WriteLine("{0:d}", DateTime.ParseExact(value, fmt, Nothing)) - Console.WriteLine() - - cal.TwoDigitYearMax = 2099 - Dim culture As CultureInfo = CType(CultureInfo.CurrentCulture.Clone(), CultureInfo) - culture.DateTimeFormat.Calendar = cal - Thread.CurrentThread.CurrentCulture = culture + Public Sub Main() + Dim fmt As String = "dd-MMM-yy" + Dim value As String = "24-Jan-49" - Console.WriteLine("Two Digit Year Range: {0} - {1}", - cal.TwoDigitYearMax - 99, cal.TwoDigitYearMax) - Console.WriteLine("{0:d}", DateTime.ParseExact(value, fmt, Nothing)) - End Sub + Dim cal As Calendar = CType(CultureInfo.CurrentCulture.Calendar.Clone(), Calendar) + Console.WriteLine("Two Digit Year Range: {0} - {1}", + cal.TwoDigitYearMax - 99, cal.TwoDigitYearMax) + + Console.WriteLine("{0:d}", DateTime.ParseExact(value, fmt, Nothing)) + Console.WriteLine() + + cal.TwoDigitYearMax = 2099 + Dim culture As CultureInfo = CType(CultureInfo.CurrentCulture.Clone(), CultureInfo) + culture.DateTimeFormat.Calendar = cal + Thread.CurrentThread.CurrentCulture = culture + + Console.WriteLine("Two Digit Year Range: {0} - {1}", + cal.TwoDigitYearMax - 99, cal.TwoDigitYearMax) + Console.WriteLine("{0:d}", DateTime.ParseExact(value, fmt, Nothing)) + End Sub End Module ' The example displays the following output: ' Two Digit Year Range: 1930 - 2029 diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/RoundTrip1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/RoundTrip1.vb index 7b55943b434ed..8934db0e6108c 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/RoundTrip1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/RoundTrip1.vb @@ -4,41 +4,41 @@ Option Strict On Imports System.Globalization Module Example - Public Sub Main() - ' - ' Round-trip DateTime values. - Dim originalDate, newDate As Date - Dim dateString As String - ' Round-trip a local time. - originalDate = Date.SpecifyKind(#4/10/2008 6:30AM#, DateTimeKind.Local) - dateString = originalDate.ToString("o") - newDate = Date.Parse(dateString, Nothing, DateTimeStyles.RoundtripKind) - Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, _ - newDate, newDate.Kind) - ' Round-trip a UTC time. - originalDate = Date.SpecifyKind(#4/12/2008 9:30AM#, DateTimeKind.Utc) - dateString = originalDate.ToString("o") - newDate = Date.Parse(dateString, Nothing, DateTimeStyles.RoundtripKind) - Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, _ - newDate, newDate.Kind) - ' Round-trip time in an unspecified time zone. - originalDate = Date.SpecifyKind(#4/13/2008 12:30PM#, DateTimeKind.Unspecified) - dateString = originalDate.ToString("o") - newDate = Date.Parse(dateString, Nothing, DateTimeStyles.RoundtripKind) - Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, _ - newDate, newDate.Kind) + Public Sub Main() + ' + ' Round-trip DateTime values. + Dim originalDate, newDate As Date + Dim dateString As String + ' Round-trip a local time. + originalDate = Date.SpecifyKind(#4/10/2008 6:30AM#, DateTimeKind.Local) + dateString = originalDate.ToString("o") + newDate = Date.Parse(dateString, Nothing, DateTimeStyles.RoundtripKind) + Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, _ + newDate, newDate.Kind) + ' Round-trip a UTC time. + originalDate = Date.SpecifyKind(#4/12/2008 9:30AM#, DateTimeKind.Utc) + dateString = originalDate.ToString("o") + newDate = Date.Parse(dateString, Nothing, DateTimeStyles.RoundtripKind) + Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, _ + newDate, newDate.Kind) + ' Round-trip time in an unspecified time zone. + originalDate = Date.SpecifyKind(#4/13/2008 12:30PM#, DateTimeKind.Unspecified) + dateString = originalDate.ToString("o") + newDate = Date.Parse(dateString, Nothing, DateTimeStyles.RoundtripKind) + Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, _ + newDate, newDate.Kind) - ' Round-trip a DateTimeOffset value. - Dim originalDTO As New DateTimeOffset(#4/12/2008 9:30AM#, New TimeSpan(-8, 0, 0)) - dateString = originalDTO.ToString("o") - Dim newDTO As DateTimeOffset = DateTimeOffset.Parse(dateString, Nothing, DateTimeStyles.RoundtripKind) - Console.WriteLine("Round-tripped {0} to {1}.", originalDTO, newDTO) - ' The example displays the following output: - ' Round-tripped 4/10/2008 6:30:00 AM Local to 4/10/2008 6:30:00 AM Local. - ' Round-tripped 4/12/2008 9:30:00 AM Utc to 4/12/2008 9:30:00 AM Utc. - ' Round-tripped 4/13/2008 12:30:00 PM Unspecified to 4/13/2008 12:30:00 PM Unspecified. - ' Round-tripped 4/12/2008 9:30:00 AM -08:00 to 4/12/2008 9:30:00 AM -08:00. - ' - End Sub + ' Round-trip a DateTimeOffset value. + Dim originalDTO As New DateTimeOffset(#4/12/2008 9:30AM#, New TimeSpan(-8, 0, 0)) + dateString = originalDTO.ToString("o") + Dim newDTO As DateTimeOffset = DateTimeOffset.Parse(dateString, Nothing, DateTimeStyles.RoundtripKind) + Console.WriteLine("Round-tripped {0} to {1}.", originalDTO, newDTO) + ' The example displays the following output: + ' Round-tripped 4/10/2008 6:30:00 AM Local to 4/10/2008 6:30:00 AM Local. + ' Round-tripped 4/12/2008 9:30:00 AM Utc to 4/12/2008 9:30:00 AM Utc. + ' Round-tripped 4/13/2008 12:30:00 PM Unspecified to 4/13/2008 12:30:00 PM Unspecified. + ' Round-tripped 4/12/2008 9:30:00 AM -08:00 to 4/12/2008 9:30:00 AM -08:00. + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/Standard1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/Standard1.vb index afd7ba7f996f0..db497b0c78f7f 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/Standard1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/Standard1.vb @@ -5,252 +5,252 @@ Imports System.Globalization Module modMain - Public Sub Main() - Console.Clear() - Console.WRiteLine() - Console.WriteLine("***d Specifier***") - Show_dSpecifier() - Console.WRiteLine() - Console.WriteLine("***D Specifier***") - ShowDSpecifier() - Console.WRiteLine() - Console.WriteLine("***f Specifier***") - Show_fSpecifier() - Console.WRiteLine() - Console.WriteLine("***F Specifier***") - ShowFSpecifier() - Console.WRiteLine() - Console.WriteLine("***g Specifier***") - Show_gSpecifier() - Console.WRiteLine() - Console.WriteLine("***G Specifier***") - ShowGSpecifier() - Console.WRiteLine() - Console.WriteLine("***M Specifier***") - ShowMSpecifier() - Console.WRiteLine() - Console.WriteLine("***O Specifier***") - ShowOSpecifier() - Console.WRiteLine() - Console.WriteLine("***R Specifier***") - ShowRSpecifier() - Console.WRiteLine() - Console.WriteLine("***S Specifier***") - ShowSSpecifier() - Console.WRiteLine() - Console.WriteLine("***t Specifier***") - Show_tSpecifier() - Console.WRiteLine() - Console.WriteLine("***T Specifier***") - ShowTSpecifier() - Console.WRiteLine() - Console.WriteLine("***u Specifier***") - Show_uSpecifier() - Console.WRiteLine() - Console.WriteLine("***U Specifier***") - ShowUSpecifier() - Console.WRiteLine() - Console.WriteLine("***Y Specifier***") - ShowYSpecifier() - End Sub - - Private Sub Show_dSpecifier() - ' d Format Specifier - ' - Dim date1 As Date = #4/10/2008# - Console.WriteLine(date1.ToString("d", DateTimeFormatInfo.InvariantInfo)) - ' Displays 04/10/2008 - Console.WriteLine(date1.ToString("d", _ - CultureInfo.CreateSpecificCulture("en-US"))) - ' Displays 4/10/2008 - Console.WriteLine(date1.ToString("d", _ - CultureInfo.CreateSpecificCulture("en-NZ"))) - ' Displays 10/04/2008 - Console.WriteLine(date1.ToString("d", _ - CultureInfo.CreateSpecificCulture("de-DE"))) - ' Displays 10.04.2008 - ' - End Sub - - Private Sub ShowDSpecifier() - ' D Format Specifier - ' - Dim date1 As Date = #4/10/2008# - Console.WriteLine(date1.ToString("D", _ - CultureInfo.CreateSpecificCulture("en-US"))) - ' Displays Thursday, April 10, 2008 - Console.WriteLine(date1.ToString("D", _ - CultureInfo.CreateSpecificCulture("pt-BR"))) - ' Displays quinta-feira, 10 de abril de 2008 - Console.WriteLine(date1.ToString("D", _ - CultureInfo.CreateSpecificCulture("es-MX"))) - ' Displays jueves, 10 de abril de 2008 - ' - End Sub - - Private Sub Show_fSpecifier() - ' f Format Specifier - ' - Dim date1 As Date = #4/10/2008 6:30AM# - Console.WriteLine(date1.ToString("f", _ - CultureInfo.CreateSpecificCulture("en-US"))) - ' Displays Thursday, April 10, 2008 6:30 AM - Console.WriteLine(date1.ToString("f", _ - CultureInfo.CreateSpecificCulture("fr-FR"))) - ' Displays jeudi 10 avril 2008 06:30 - ' - End Sub - - Private Sub ShowFSpecifier() - ' F Format Specifier - ' - Dim date1 As Date = #4/10/2008 6:30AM# - Console.WriteLine(date1.ToString("F", _ - CultureInfo.CreateSpecificCulture("en-US"))) - ' Displays Thursday, April 10, 2008 6:30:00 AM - Console.WriteLine(date1.ToString("F", _ - CultureInfo.CreateSpecificCulture("fr-FR"))) - ' Displays jeudi 10 avril 2008 06:30:00 - ' - End Sub + Public Sub Main() + Console.Clear() + Console.WRiteLine() + Console.WriteLine("***d Specifier***") + Show_dSpecifier() + Console.WRiteLine() + Console.WriteLine("***D Specifier***") + ShowDSpecifier() + Console.WRiteLine() + Console.WriteLine("***f Specifier***") + Show_fSpecifier() + Console.WRiteLine() + Console.WriteLine("***F Specifier***") + ShowFSpecifier() + Console.WRiteLine() + Console.WriteLine("***g Specifier***") + Show_gSpecifier() + Console.WRiteLine() + Console.WriteLine("***G Specifier***") + ShowGSpecifier() + Console.WRiteLine() + Console.WriteLine("***M Specifier***") + ShowMSpecifier() + Console.WRiteLine() + Console.WriteLine("***O Specifier***") + ShowOSpecifier() + Console.WRiteLine() + Console.WriteLine("***R Specifier***") + ShowRSpecifier() + Console.WRiteLine() + Console.WriteLine("***S Specifier***") + ShowSSpecifier() + Console.WRiteLine() + Console.WriteLine("***t Specifier***") + Show_tSpecifier() + Console.WRiteLine() + Console.WriteLine("***T Specifier***") + ShowTSpecifier() + Console.WRiteLine() + Console.WriteLine("***u Specifier***") + Show_uSpecifier() + Console.WRiteLine() + Console.WriteLine("***U Specifier***") + ShowUSpecifier() + Console.WRiteLine() + Console.WriteLine("***Y Specifier***") + ShowYSpecifier() + End Sub - Private Sub Show_gSpecifier() - ' g Format Specifier - ' - Dim date1 As Date = #4/10/2008 6:30AM# - Console.WriteLine(date1.ToString("g", _ - DateTimeFormatInfo.InvariantInfo)) - ' Displays 04/10/2008 06:30 - Console.WriteLine(date1.ToString("g", _ - CultureInfo.CreateSpecificCulture("en-us"))) - ' Displays 4/10/2008 6:30 AM - Console.WriteLine(date1.ToString("g", _ - CultureInfo.CreateSpecificCulture("fr-BE"))) - ' Displays 10/04/2008 6:30 - ' - End Sub - - Private Sub ShowGSpecifier() - ' G Format Specifier - ' - Dim date1 As Date = #4/10/2008 6:30AM# - Console.WriteLine(date1.ToString("G", _ - DateTimeFormatInfo.InvariantInfo)) - ' Displays 04/10/2008 06:30:00 - Console.WriteLine(date1.ToString("G", _ - CultureInfo.CreateSpecificCulture("en-us"))) - ' Displays 4/10/2008 6:30:00 AM - Console.WriteLine(date1.ToString("G", _ - CultureInfo.CreateSpecificCulture("nl-BE"))) - ' Displays 10/04/2008 6:30:00 - ' - End Sub - - Private Sub ShowMSpecifier() - ' M Format Specifier - ' - Dim date1 As Date = #4/10/2008 6:30AM# - Console.WriteLine(date1.ToString("m", _ - CultureInfo.CreateSpecificCulture("en-us"))) - ' Displays April 10 - Console.WriteLine(date1.ToString("m", _ - CultureInfo.CreateSpecificCulture("ms-MY"))) - ' Displays 10 April - ' - End Sub - - Private Sub ShowOSpecifier() - ' O Format Specifier + Private Sub Show_dSpecifier() + ' d Format Specifier + ' + Dim date1 As Date = #4/10/2008# + Console.WriteLine(date1.ToString("d", DateTimeFormatInfo.InvariantInfo)) + ' Displays 04/10/2008 + Console.WriteLine(date1.ToString("d", _ + CultureInfo.CreateSpecificCulture("en-US"))) + ' Displays 4/10/2008 + Console.WriteLine(date1.ToString("d", _ + CultureInfo.CreateSpecificCulture("en-NZ"))) + ' Displays 10/04/2008 + Console.WriteLine(date1.ToString("d", _ + CultureInfo.CreateSpecificCulture("de-DE"))) + ' Displays 10.04.2008 + ' + End Sub - Dim date1 As Date = #4/10/2008 6:30AM# - Dim dateOffset As New DateTimeOffset(date1, TimeZoneInfo.Local.GetUtcOFfset(date1)) - Console.WriteLine(date1.ToString("o")) - ' Displays 2008-04-10T06:30:00.0000000 - Console.WriteLine(dateOffset.ToString("o")) - ' Displays 2008-04-10T06:30:00.0000000-07:00 + Private Sub ShowDSpecifier() + ' D Format Specifier + ' + Dim date1 As Date = #4/10/2008# + Console.WriteLine(date1.ToString("D", _ + CultureInfo.CreateSpecificCulture("en-US"))) + ' Displays Thursday, April 10, 2008 + Console.WriteLine(date1.ToString("D", _ + CultureInfo.CreateSpecificCulture("pt-BR"))) + ' Displays quinta-feira, 10 de abril de 2008 + Console.WriteLine(date1.ToString("D", _ + CultureInfo.CreateSpecificCulture("es-MX"))) + ' Displays jueves, 10 de abril de 2008 + ' + End Sub - End Sub - - Private Sub ShowRSpecifier() - ' R Format Specifier - ' - Dim date1 As Date = #4/10/2008 6:30AM# - Dim dateOffset As New DateTimeOffset(date1, TimeZoneInfo.Local.GetUtcOFfset(date1)) - Console.WriteLine(date1.ToUniversalTime.ToString("r")) - ' Displays Thu, 10 Apr 2008 13:30:00 GMT - Console.WriteLine(dateOffset.ToUniversalTime.ToString("r")) - ' Displays Thu, 10 Apr 2008 13:30:00 GMT - ' - End Sub - - Private Sub ShowSSpecifier() - ' S Format Specifier - ' - Dim date1 As Date = #4/10/2008 6:30AM# - Console.WriteLine(date1.ToString("s")) - ' Displays 2008-04-10T06:30:00 - ' - End Sub + Private Sub Show_fSpecifier() + ' f Format Specifier + ' + Dim date1 As Date = #4/10/2008 6:30AM# + Console.WriteLine(date1.ToString("f", _ + CultureInfo.CreateSpecificCulture("en-US"))) + ' Displays Thursday, April 10, 2008 6:30 AM + Console.WriteLine(date1.ToString("f", _ + CultureInfo.CreateSpecificCulture("fr-FR"))) + ' Displays jeudi 10 avril 2008 06:30 + ' + End Sub - Private Sub Show_tSpecifier() - ' t Format Specifier - ' - Dim date1 As Date = #4/10/2008 6:30AM# - Console.WriteLine(date1.ToString("t", _ - CultureInfo.CreateSpecificCulture("en-us"))) - ' Displays 6:30 AM - Console.WriteLine(date1.ToString("t", _ - CultureInfo.CreateSpecificCulture("es-ES"))) - ' Displays 6:30 - ' - End Sub - - Private Sub ShowTSpecifier() - ' T Format Specifier - ' - Dim date1 As Date = #4/10/2008 6:30AM# - Console.WriteLine(date1.ToString("T", _ - CultureInfo.CreateSpecificCulture("en-us"))) - ' Displays 6:30:00 AM - Console.WriteLine(date1.ToString("T", _ - CultureInfo.CreateSpecificCulture("es-ES"))) - ' Displays 6:30:00 - ' - End Sub - - Private Sub Show_uSpecifier() - ' u Format Specifier - ' - Dim date1 As Date = #4/10/2008 6:30AM# - Console.WriteLine(date1.ToUniversalTime.ToString("u")) - ' Displays 2008-04-10 13:30:00Z - ' - End Sub - - Private Sub ShowUSpecifier() - ' U Format Specifier - ' - Dim date1 As Date = #4/10/2008 6:30AM# - Console.WriteLine(date1.ToString("U", CultureInfo.CreateSpecificCulture("en-US"))) - ' Displays Thursday, April 10, 2008 1:30:00 PM - Console.WriteLine(date1.ToString("U", CultureInfo.CreateSpecificCulture("sv-FI"))) - ' Displays den 10 april 2008 13:30:00 - ' - End Sub - - Private Sub ShowYSpecifier() - ' Y/y Format Specifier - ' - Dim date1 As Date = #4/10/2008 6:30AM# - Console.WriteLine(date1.ToString("Y", CultureInfo.CreateSpecificCulture("en-US"))) - ' Displays April, 2008 - Console.WriteLine(date1.ToString("y", CultureInfo.CreateSpecificCulture("af-ZA"))) - ' Displays April 2008 - ' - End Sub + Private Sub ShowFSpecifier() + ' F Format Specifier + ' + Dim date1 As Date = #4/10/2008 6:30AM# + Console.WriteLine(date1.ToString("F", _ + CultureInfo.CreateSpecificCulture("en-US"))) + ' Displays Thursday, April 10, 2008 6:30:00 AM + Console.WriteLine(date1.ToString("F", _ + CultureInfo.CreateSpecificCulture("fr-FR"))) + ' Displays jeudi 10 avril 2008 06:30:00 + ' + End Sub + + Private Sub Show_gSpecifier() + ' g Format Specifier + ' + Dim date1 As Date = #4/10/2008 6:30AM# + Console.WriteLine(date1.ToString("g", _ + DateTimeFormatInfo.InvariantInfo)) + ' Displays 04/10/2008 06:30 + Console.WriteLine(date1.ToString("g", _ + CultureInfo.CreateSpecificCulture("en-us"))) + ' Displays 4/10/2008 6:30 AM + Console.WriteLine(date1.ToString("g", _ + CultureInfo.CreateSpecificCulture("fr-BE"))) + ' Displays 10/04/2008 6:30 + ' + End Sub + + Private Sub ShowGSpecifier() + ' G Format Specifier + ' + Dim date1 As Date = #4/10/2008 6:30AM# + Console.WriteLine(date1.ToString("G", _ + DateTimeFormatInfo.InvariantInfo)) + ' Displays 04/10/2008 06:30:00 + Console.WriteLine(date1.ToString("G", _ + CultureInfo.CreateSpecificCulture("en-us"))) + ' Displays 4/10/2008 6:30:00 AM + Console.WriteLine(date1.ToString("G", _ + CultureInfo.CreateSpecificCulture("nl-BE"))) + ' Displays 10/04/2008 6:30:00 + ' + End Sub + + Private Sub ShowMSpecifier() + ' M Format Specifier + ' + Dim date1 As Date = #4/10/2008 6:30AM# + Console.WriteLine(date1.ToString("m", _ + CultureInfo.CreateSpecificCulture("en-us"))) + ' Displays April 10 + Console.WriteLine(date1.ToString("m", _ + CultureInfo.CreateSpecificCulture("ms-MY"))) + ' Displays 10 April + ' + End Sub + + Private Sub ShowOSpecifier() + ' O Format Specifier + + Dim date1 As Date = #4/10/2008 6:30AM# + Dim dateOffset As New DateTimeOffset(date1, TimeZoneInfo.Local.GetUtcOFfset(date1)) + Console.WriteLine(date1.ToString("o")) + ' Displays 2008-04-10T06:30:00.0000000 + Console.WriteLine(dateOffset.ToString("o")) + ' Displays 2008-04-10T06:30:00.0000000-07:00 + + End Sub + + Private Sub ShowRSpecifier() + ' R Format Specifier + ' + Dim date1 As Date = #4/10/2008 6:30AM# + Dim dateOffset As New DateTimeOffset(date1, TimeZoneInfo.Local.GetUtcOFfset(date1)) + Console.WriteLine(date1.ToUniversalTime.ToString("r")) + ' Displays Thu, 10 Apr 2008 13:30:00 GMT + Console.WriteLine(dateOffset.ToUniversalTime.ToString("r")) + ' Displays Thu, 10 Apr 2008 13:30:00 GMT + ' + End Sub + + Private Sub ShowSSpecifier() + ' S Format Specifier + ' + Dim date1 As Date = #4/10/2008 6:30AM# + Console.WriteLine(date1.ToString("s")) + ' Displays 2008-04-10T06:30:00 + ' + End Sub + + Private Sub Show_tSpecifier() + ' t Format Specifier + ' + Dim date1 As Date = #4/10/2008 6:30AM# + Console.WriteLine(date1.ToString("t", _ + CultureInfo.CreateSpecificCulture("en-us"))) + ' Displays 6:30 AM + Console.WriteLine(date1.ToString("t", _ + CultureInfo.CreateSpecificCulture("es-ES"))) + ' Displays 6:30 + ' + End Sub + + Private Sub ShowTSpecifier() + ' T Format Specifier + ' + Dim date1 As Date = #4/10/2008 6:30AM# + Console.WriteLine(date1.ToString("T", _ + CultureInfo.CreateSpecificCulture("en-us"))) + ' Displays 6:30:00 AM + Console.WriteLine(date1.ToString("T", _ + CultureInfo.CreateSpecificCulture("es-ES"))) + ' Displays 6:30:00 + ' + End Sub + + Private Sub Show_uSpecifier() + ' u Format Specifier + ' + Dim date1 As Date = #4/10/2008 6:30AM# + Console.WriteLine(date1.ToUniversalTime.ToString("u")) + ' Displays 2008-04-10 13:30:00Z + ' + End Sub + + Private Sub ShowUSpecifier() + ' U Format Specifier + ' + Dim date1 As Date = #4/10/2008 6:30AM# + Console.WriteLine(date1.ToString("U", CultureInfo.CreateSpecificCulture("en-US"))) + ' Displays Thursday, April 10, 2008 1:30:00 PM + Console.WriteLine(date1.ToString("U", CultureInfo.CreateSpecificCulture("sv-FI"))) + ' Displays den 10 april 2008 13:30:00 + ' + End Sub + + Private Sub ShowYSpecifier() + ' Y/y Format Specifier + ' + Dim date1 As Date = #4/10/2008 6:30AM# + Console.WriteLine(date1.ToString("Y", CultureInfo.CreateSpecificCulture("en-US"))) + ' Displays April, 2008 + Console.WriteLine(date1.ToString("y", CultureInfo.CreateSpecificCulture("af-ZA"))) + ' Displays April 2008 + ' + End Sub End Module - + diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/o1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/o1.vb index 5304dd441477b..910809626ef14 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/o1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/o1.vb @@ -3,21 +3,21 @@ Option Strict On ' Module Example - Public Sub Main() - Dim dat As New Date(2009, 6, 15, 13, 45, 30, - DateTimeKind.Unspecified) - Console.WriteLine("{0} ({1}) --> {0:O}", dat, dat.Kind) - - Dim uDat As New Date(2009, 6, 15, 13, 45, 30, DateTimeKind.Utc) - Console.WriteLine("{0} ({1}) --> {0:O}", uDat, uDat.Kind) - - Dim lDat As New Date(2009, 6, 15, 13, 45, 30, DateTimeKind.Local) - Console.WriteLine("{0} ({1}) --> {0:O}", lDat, lDat.Kind) - Console.WriteLine() - - Dim dto As New DateTimeOffset(lDat) - Console.WriteLine("{0} --> {0:O}", dto) - End Sub + Public Sub Main() + Dim dat As New Date(2009, 6, 15, 13, 45, 30, + DateTimeKind.Unspecified) + Console.WriteLine("{0} ({1}) --> {0:O}", dat, dat.Kind) + + Dim uDat As New Date(2009, 6, 15, 13, 45, 30, DateTimeKind.Utc) + Console.WriteLine("{0} ({1}) --> {0:O}", uDat, uDat.Kind) + + Dim lDat As New Date(2009, 6, 15, 13, 45, 30, DateTimeKind.Local) + Console.WriteLine("{0} ({1}) --> {0:O}", lDat, lDat.Kind) + Console.WriteLine() + + Dim dto As New DateTimeOffset(lDat) + Console.WriteLine("{0} --> {0:O}", dto) + End Sub End Module ' The example displays the following output: ' 6/15/2009 1:45:30 PM (Unspecified) --> 2009-06-15T13:45:30.0000000 diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/stdandparsing1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/stdandparsing1.vb index 8f9a140c6fdd6..b78ff4e2f60c7 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/stdandparsing1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Standard/vb/stdandparsing1.vb @@ -5,12 +5,12 @@ Option Strict On Imports System.Globalization Module Example - Public Sub Main() - Console.WriteLine("'d' standard format string:") - For Each customString In DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns("d"c) - Console.WriteLine(" {0}", customString) - Next - End Sub + Public Sub Main() + Console.WriteLine("'d' standard format string:") + For Each customString In DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns("d"c) + Console.WriteLine(" {0}", customString) + Next + End Sub End Module ' The example displays the following output: ' 'd' standard format string: diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Enum/vb/enum1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Enum/vb/enum1.vb index d44cf301d59a8..1c1ab0efb32ec 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Enum/vb/enum1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Enum/vb/enum1.vb @@ -5,86 +5,86 @@ Imports System.IO ' Public Enum Color - Red = 1 - Blue = 2 - Green = 3 + Red = 1 + Blue = 2 + Green = 3 End Enum ' Module modMain - Public Sub Main() - ShowGSpecifier() - ShowFSpecifier() - ShowDSpecifier() - ShowXSpecifier() - ShowExample() - End Sub - - Private Sub ShowGSpecifier() - Console.WriteLine("G Specifier:") - ' - Console.WriteLine(ConsoleColor.Red.ToString("G")) ' Displays Red - Dim attributes As FileAttributes = FileAttributes.Hidden Or _ - FileAttributes.Archive - Console.WriteLine(attributes.ToString("G")) ' Displays Hidden, Archive - ' - Console.WriteLine() - End Sub - - Private Sub ShowFSpecifier() - Console.WriteLine("F Specifier:") - ' - Console.WriteLine(ConsoleColor.Blue.ToString("F")) ' Displays Blue - Dim attributes As FileAttributes = FileAttributes.Hidden Or _ - FileAttributes.Archive - Console.WriteLine(attributes.ToString("F")) ' Displays Hidden, Archive - ' - Console.WriteLine() - End Sub - - Private Sub ShowDSpecifier() - Console.WriteLine("D Specifier:") - ' - Console.WriteLine(ConsoleColor.Cyan.ToString("D")) ' Displays 11 - Dim attributes As FileAttributes = FileAttributes.Hidden Or _ - FileAttributes.Archive - Console.WriteLine(attributes.ToString("D")) ' Displays 34 - ' - Console.WriteLine() - End Sub - - Private Sub ShowXSpecifier() - Console.WriteLine("X Specifier:") - ' - Console.WriteLine(ConsoleColor.Cyan.ToString("X")) ' Displays 0000000B - Dim attributes As FileAttributes = FileAttributes.Hidden Or _ - FileAttributes.Archive - Console.WriteLine(attributes.ToString("X")) ' Displays 00000022 - ' - Console.WriteLine() - End Sub + Public Sub Main() + ShowGSpecifier() + ShowFSpecifier() + ShowDSpecifier() + ShowXSpecifier() + ShowExample() + End Sub - Private Sub ShowExample() - Console.WriteLine("Example:") - ' - Dim myColor As Color = Color.Green - ' - - ' - Console.WriteLine("The value of myColor is {0}.", _ - myColor.ToString("G")) - Console.WriteLine("The value of myColor is {0}.", _ - myColor.ToString("F")) - Console.WriteLine("The value of myColor is {0}.", _ - myColor.ToString("D")) - Console.WriteLine("The value of myColor is 0x{0}.", _ - myColor.ToString("X")) - ' The example displays the following output to the console: - ' The value of myColor is Green. - ' The value of myColor is Green. - ' The value of myColor is 3. - ' The value of myColor is 0x00000003. - ' - End Sub + Private Sub ShowGSpecifier() + Console.WriteLine("G Specifier:") + ' + Console.WriteLine(ConsoleColor.Red.ToString("G")) ' Displays Red + Dim attributes As FileAttributes = FileAttributes.Hidden Or _ + FileAttributes.Archive + Console.WriteLine(attributes.ToString("G")) ' Displays Hidden, Archive + ' + Console.WriteLine() + End Sub + + Private Sub ShowFSpecifier() + Console.WriteLine("F Specifier:") + ' + Console.WriteLine(ConsoleColor.Blue.ToString("F")) ' Displays Blue + Dim attributes As FileAttributes = FileAttributes.Hidden Or _ + FileAttributes.Archive + Console.WriteLine(attributes.ToString("F")) ' Displays Hidden, Archive + ' + Console.WriteLine() + End Sub + + Private Sub ShowDSpecifier() + Console.WriteLine("D Specifier:") + ' + Console.WriteLine(ConsoleColor.Cyan.ToString("D")) ' Displays 11 + Dim attributes As FileAttributes = FileAttributes.Hidden Or _ + FileAttributes.Archive + Console.WriteLine(attributes.ToString("D")) ' Displays 34 + ' + Console.WriteLine() + End Sub + + Private Sub ShowXSpecifier() + Console.WriteLine("X Specifier:") + ' + Console.WriteLine(ConsoleColor.Cyan.ToString("X")) ' Displays 0000000B + Dim attributes As FileAttributes = FileAttributes.Hidden Or _ + FileAttributes.Archive + Console.WriteLine(attributes.ToString("X")) ' Displays 00000022 + ' + Console.WriteLine() + End Sub + + Private Sub ShowExample() + Console.WriteLine("Example:") + ' + Dim myColor As Color = Color.Green + ' + + ' + Console.WriteLine("The value of myColor is {0}.", _ + myColor.ToString("G")) + Console.WriteLine("The value of myColor is {0}.", _ + myColor.ToString("F")) + Console.WriteLine("The value of myColor is {0}.", _ + myColor.ToString("D")) + Console.WriteLine("The value of myColor is 0x{0}.", _ + myColor.ToString("X")) + ' The example displays the following output to the console: + ' The value of myColor is Green. + ' The value of myColor is Green. + ' The value of myColor is 3. + ' The value of myColor is 0x00000003. + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.Calendar/vb/Calendar1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.Calendar/vb/Calendar1.vb index e5b3b7d4772c2..ed15a3e26e4ce 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.Calendar/vb/Calendar1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.Calendar/vb/Calendar1.vb @@ -5,91 +5,91 @@ Option Strict On Imports System.Globalization Public Class CalendarDates - Public Shared Sub Main() - Dim hijriCal As New HijriCalendar() - Dim hijriUtil As New CalendarUtility(hijriCal) - Dim dateValue1 As Date = New Date(1429, 6, 29, hijriCal) - Dim dateValue2 As DateTimeOffset = New DateTimeOffset(dateValue1, _ - TimeZoneInfo.Local.GetUtcOffset(dateValue1)) - Dim jc As CultureInfo = CultureInfo.CreateSpecificCulture("ar-JO") - - ' Display the date using the Gregorian calendar. - Console.WriteLine("Using the system default culture: {0}", _ - dateValue1.ToString("d")) - ' Display the date using the ar-JO culture's original default calendar. - Console.WriteLine("Using the ar-JO culture's original default calendar: {0}", _ - dateValue1.ToString("d", jc)) - ' Display the date using the Hijri calendar. - Console.WriteLine("Using the ar-JO culture with Hijri as the default calendar:") - ' Display a Date value. - Console.WriteLine(hijriUtil.DisplayDate(dateValue1, jc)) - ' Display a DateTimeOffset value. - Console.WriteLine(hijriUtil.DisplayDate(dateValue2, jc)) - - Console.WriteLine() - - Dim persianCal As New PersianCalendar() - Dim persianUtil As New CalendarUtility(persianCal) - Dim ic As CultureInfo = CultureInfo.CreateSpecificCulture("fa-IR") - - ' Display the date using the ir-FA culture's default calendar. - Console.WriteLine("Using the ir-FA culture's default calendar: {0}", _ - dateValue1.ToString("d", ic)) - ' Display a Date value. - Console.WriteLine(persianUtil.DisplayDate(dateValue1, ic)) - ' Display a DateTimeOffset value. - Console.WriteLine(persianUtil.DisplayDate(dateValue2, ic)) - End Sub + Public Shared Sub Main() + Dim hijriCal As New HijriCalendar() + Dim hijriUtil As New CalendarUtility(hijriCal) + Dim dateValue1 As Date = New Date(1429, 6, 29, hijriCal) + Dim dateValue2 As DateTimeOffset = New DateTimeOffset(dateValue1, _ + TimeZoneInfo.Local.GetUtcOffset(dateValue1)) + Dim jc As CultureInfo = CultureInfo.CreateSpecificCulture("ar-JO") + + ' Display the date using the Gregorian calendar. + Console.WriteLine("Using the system default culture: {0}", _ + dateValue1.ToString("d")) + ' Display the date using the ar-JO culture's original default calendar. + Console.WriteLine("Using the ar-JO culture's original default calendar: {0}", _ + dateValue1.ToString("d", jc)) + ' Display the date using the Hijri calendar. + Console.WriteLine("Using the ar-JO culture with Hijri as the default calendar:") + ' Display a Date value. + Console.WriteLine(hijriUtil.DisplayDate(dateValue1, jc)) + ' Display a DateTimeOffset value. + Console.WriteLine(hijriUtil.DisplayDate(dateValue2, jc)) + + Console.WriteLine() + + Dim persianCal As New PersianCalendar() + Dim persianUtil As New CalendarUtility(persianCal) + Dim ic As CultureInfo = CultureInfo.CreateSpecificCulture("fa-IR") + + ' Display the date using the ir-FA culture's default calendar. + Console.WriteLine("Using the ir-FA culture's default calendar: {0}", _ + dateValue1.ToString("d", ic)) + ' Display a Date value. + Console.WriteLine(persianUtil.DisplayDate(dateValue1, ic)) + ' Display a DateTimeOffset value. + Console.WriteLine(persianUtil.DisplayDate(dateValue2, ic)) + End Sub End Class Public Class CalendarUtility - Private thisCalendar As Calendar - Private targetCulture As CultureInfo - - Public Sub New(cal As Calendar) - Me.thisCalendar = cal - End Sub - - Private Function CalendarExists(culture As CultureInfo) As Boolean - Me.targetCulture = culture - Return Array.Exists(Me.targetCulture.OptionalCalendars, _ - AddressOf Me.HasSameName) - End Function - - Private Function HasSameName(cal As Calendar) As Boolean - If cal.ToString() = thisCalendar.ToString() Then - Return True - Else - Return False - End If - End Function - - Public Function DisplayDate(dateToDisplay As Date, _ - culture As CultureInfo) As String - Dim displayOffsetDate As DateTimeOffset = dateToDisplay - Return DisplayDate(displayOffsetDate, culture) - End Function - - Public Function DisplayDate(dateToDisplay As DateTimeOffset, _ - culture As CultureInfo) As String - Dim specifier As String = "yyyy/MM/dd" - - If Me.CalendarExists(culture) Then - Console.WriteLine("Displaying date in supported {0} calendar...", _ - thisCalendar.GetType().Name) - culture.DateTimeFormat.Calendar = Me.thisCalendar - Return dateToDisplay.ToString(specifier, culture) - Else - Console.WriteLine("Displaying date in unsupported {0} calendar...", _ - thisCalendar.GetType().Name) - - Dim separator As String = targetCulture.DateTimeFormat.DateSeparator - - Return thisCalendar.GetYear(dateToDisplay.DateTime).ToString("0000") & separator & _ - thisCalendar.GetMonth(dateToDisplay.DateTime).ToString("00") & separator & _ - thisCalendar.GetDayOfMonth(dateToDisplay.DateTime).ToString("00") - End If - End Function + Private thisCalendar As Calendar + Private targetCulture As CultureInfo + + Public Sub New(cal As Calendar) + Me.thisCalendar = cal + End Sub + + Private Function CalendarExists(culture As CultureInfo) As Boolean + Me.targetCulture = culture + Return Array.Exists(Me.targetCulture.OptionalCalendars, _ + AddressOf Me.HasSameName) + End Function + + Private Function HasSameName(cal As Calendar) As Boolean + If cal.ToString() = thisCalendar.ToString() Then + Return True + Else + Return False + End If + End Function + + Public Function DisplayDate(dateToDisplay As Date, _ + culture As CultureInfo) As String + Dim displayOffsetDate As DateTimeOffset = dateToDisplay + Return DisplayDate(displayOffsetDate, culture) + End Function + + Public Function DisplayDate(dateToDisplay As DateTimeOffset, _ + culture As CultureInfo) As String + Dim specifier As String = "yyyy/MM/dd" + + If Me.CalendarExists(culture) Then + Console.WriteLine("Displaying date in supported {0} calendar...", _ + thisCalendar.GetType().Name) + culture.DateTimeFormat.Calendar = Me.thisCalendar + Return dateToDisplay.ToString(specifier, culture) + Else + Console.WriteLine("Displaying date in unsupported {0} calendar...", _ + thisCalendar.GetType().Name) + + Dim separator As String = targetCulture.DateTimeFormat.DateSeparator + + Return thisCalendar.GetYear(dateToDisplay.DateTime).ToString("0000") & separator & _ + thisCalendar.GetMonth(dateToDisplay.DateTime).ToString("00") & separator & _ + thisCalendar.GetDayOfMonth(dateToDisplay.DateTime).ToString("00") + End If + End Function End Class ' The example displays the following output to the console: ' Using the system default culture: 7/3/2008 @@ -108,19 +108,19 @@ End Class ' Module AdditionalSnippets - Public Sub BadDate() - ' - Dim persianCal As New PersianCalendar() - - Dim persianDate As Date = persianCal.ToDateTime(1387, 3, 18, _ - 12, 0, 0, 0) - Console.WriteLine(persianDate.ToString()) - - persianDate = New DateTime(1387, 3, 18, persianCal) - Console.WriteLine(persianDate.ToString()) - ' The example displays the following output to the console: - ' 6/7/2008 12:00:00 PM - ' 6/7/2008 12:00:00 AM - ' - End Sub + Public Sub BadDate() + ' + Dim persianCal As New PersianCalendar() + + Dim persianDate As Date = persianCal.ToDateTime(1387, 3, 18, _ + 12, 0, 0, 0) + Console.WriteLine(persianDate.ToString()) + + persianDate = New DateTime(1387, 3, 18, persianCal) + Console.WriteLine(persianDate.ToString()) + ' The example displays the following output to the console: + ' 6/7/2008 12:00:00 PM + ' 6/7/2008 12:00:00 AM + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.Millisecond/vb/Millisecond.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.Millisecond/vb/Millisecond.vb index f98e4ef1d5fe7..3069cb5828c76 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.Millisecond/vb/Millisecond.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.Millisecond/vb/Millisecond.vb @@ -6,39 +6,39 @@ Imports System.Globalization Imports System.Text.REgularExpressions Module MillisecondDisplay - Public Sub Main() + Public Sub Main() - Dim dateString As String = "7/16/2008 8:32:45.126 AM" - - Try - Dim dateValue As Date = Date.Parse(dateString) - Dim dateOffsetValue As DateTimeOffset = DateTimeOffset.Parse(dateString) - - ' Display Millisecond component alone. - Console.WriteLine("Millisecond component only: {0}", _ - dateValue.ToString("fff")) - Console.WriteLine("Millisecond component only: {0}", _ - dateOffsetValue.ToString("fff")) - - ' Display Millisecond component with full date and time. - Console.WriteLine("Date and Time with Milliseconds: {0}", _ - dateValue.ToString("MM/dd/yyyy hh:mm:ss.fff tt")) - Console.WriteLine("Date and Time with Milliseconds: {0}", _ - dateOffsetValue.ToString("MM/dd/yyyy hh:mm:ss.fff tt")) - - ' Append millisecond pattern to current culture's full date time pattern - Dim fullPattern As String = DateTimeFormatInfo.CurrentInfo.FullDateTimePattern - fullPattern = Regex.Replace(fullPattern, "(:ss|:s)", "$1.fff") - - ' Display Millisecond component with modified full date and time pattern. - Console.WriteLine("Modified full date time pattern: {0}", _ - dateValue.ToString(fullPattern)) - Console.WriteLine("Modified full date time pattern: {0}", _ - dateOffsetValue.ToString(fullPattern)) - Catch e As FormatException - Console.WriteLine("Unable to convert {0} to a date.", dateString) - End Try - End Sub + Dim dateString As String = "7/16/2008 8:32:45.126 AM" + + Try + Dim dateValue As Date = Date.Parse(dateString) + Dim dateOffsetValue As DateTimeOffset = DateTimeOffset.Parse(dateString) + + ' Display Millisecond component alone. + Console.WriteLine("Millisecond component only: {0}", _ + dateValue.ToString("fff")) + Console.WriteLine("Millisecond component only: {0}", _ + dateOffsetValue.ToString("fff")) + + ' Display Millisecond component with full date and time. + Console.WriteLine("Date and Time with Milliseconds: {0}", _ + dateValue.ToString("MM/dd/yyyy hh:mm:ss.fff tt")) + Console.WriteLine("Date and Time with Milliseconds: {0}", _ + dateOffsetValue.ToString("MM/dd/yyyy hh:mm:ss.fff tt")) + + ' Append millisecond pattern to current culture's full date time pattern + Dim fullPattern As String = DateTimeFormatInfo.CurrentInfo.FullDateTimePattern + fullPattern = Regex.Replace(fullPattern, "(:ss|:s)", "$1.fff") + + ' Display Millisecond component with modified full date and time pattern. + Console.WriteLine("Modified full date time pattern: {0}", _ + dateValue.ToString(fullPattern)) + Console.WriteLine("Modified full date time pattern: {0}", _ + dateOffsetValue.ToString(fullPattern)) + Catch e As FormatException + Console.WriteLine("Unable to convert {0} to a date.", dateString) + End Try + End Sub End Module ' The example displays the following output if the current culture is en-US: ' Millisecond component only: 126 @@ -50,29 +50,29 @@ End Module ' Public Module AdditionalSnippets - - Public Sub Show - ' - Dim dateValue As New Date(2008, 7, 16, 8, 32, 45, 180) - Console.WriteLIne(dateValue.ToString("fff")) - Console.WriteLine(dateValue.ToString("FFF")) - ' The example displays the following output to the console: - ' 180 - ' 18 - ' - End Sub - Public Sub Show2() - ' - Dim dateValue As New DateTime(2008, 7, 16, 8, 32, 45, 180) - Console.WriteLine("{0} seconds", dateValue.ToString("s.f")) - Console.WriteLine("{0} seconds", dateValue.ToString("s.ff")) - Console.WriteLine("{0} seconds", dateValue.ToString("s.ffff")) - ' The example displays the following output to the console: - ' 45.1 seconds - ' 45.18 seconds - ' 45.1800 seconds - ' - End Sub - + Public Sub Show + ' + Dim dateValue As New Date(2008, 7, 16, 8, 32, 45, 180) + Console.WriteLIne(dateValue.ToString("fff")) + Console.WriteLine(dateValue.ToString("FFF")) + ' The example displays the following output to the console: + ' 180 + ' 18 + ' + End Sub + + Public Sub Show2() + ' + Dim dateValue As New DateTime(2008, 7, 16, 8, 32, 45, 180) + Console.WriteLine("{0} seconds", dateValue.ToString("s.f")) + Console.WriteLine("{0} seconds", dateValue.ToString("s.ff")) + Console.WriteLine("{0} seconds", dateValue.ToString("s.ffff")) + ' The example displays the following output to the console: + ' 45.1 seconds + ' 45.18 seconds + ' 45.1800 seconds + ' + End Sub + End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.NumericValue/vb/Telephone1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.NumericValue/vb/Telephone1.vb index bc12b0a844139..e5fccb36f4c78 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.NumericValue/vb/Telephone1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.NumericValue/vb/Telephone1.vb @@ -3,71 +3,71 @@ Option Strict On ' Public Class TelephoneFormatter : Implements IFormatProvider, ICustomFormatter - 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 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 - ' Check whether this is an appropriate callback - If Not Me.Equals(formatProvider) Then Return Nothing + Public Function Format(fmt As String, arg As Object, _ + formatProvider As IFormatProvider) As String _ + Implements ICustomFormatter.Format + ' Check whether this is an appropriate callback + If Not Me.Equals(formatProvider) Then Return Nothing - ' Set default format specifier - If String.IsNullOrEmpty(fmt) Then fmt = "N" + ' Set default format specifier + If String.IsNullOrEmpty(fmt) Then fmt = "N" - Dim numericString As String = arg.ToString - - If fmt = "N" Then - Select Case numericString.Length - Case <= 4 - Return numericString - Case 7 - Return Left(numericString, 3) & "-" & Mid(numericString, 4) - Case 10 - Return "(" & Left(numericString, 3) & ") " & _ - Mid(numericString, 4, 3) & "-" & Mid(numericString, 7) - Case Else - Throw New FormatException( _ - String.Format("'{0}' cannot be used to format {1}.", _ - fmt, arg.ToString())) - End Select - ElseIf fmt = "I" Then - If numericString.Length < 10 Then - Throw New FormatException(String.Format("{0} does not have 10 digits.", arg.ToString())) - Else - numericString = "+1 " & Left(numericString, 3) & " " & Mid(numericString, 4, 3) & " " & Mid(numericString, 7) - End If - Else - Throw New FormatException(String.Format("The {0} format specifier is invalid.", fmt)) - End If - Return numericString - End Function + Dim numericString As String = arg.ToString + + If fmt = "N" Then + Select Case numericString.Length + Case <= 4 + Return numericString + Case 7 + Return Left(numericString, 3) & "-" & Mid(numericString, 4) + Case 10 + Return "(" & Left(numericString, 3) & ") " & _ + Mid(numericString, 4, 3) & "-" & Mid(numericString, 7) + Case Else + Throw New FormatException( _ + String.Format("'{0}' cannot be used to format {1}.", _ + fmt, arg.ToString())) + End Select + ElseIf fmt = "I" Then + If numericString.Length < 10 Then + Throw New FormatException(String.Format("{0} does not have 10 digits.", arg.ToString())) + Else + numericString = "+1 " & Left(numericString, 3) & " " & Mid(numericString, 4, 3) & " " & Mid(numericString, 7) + End If + Else + Throw New FormatException(String.Format("The {0} format specifier is invalid.", fmt)) + End If + Return numericString + End Function End Class Public Module TestTelephoneFormatter - Public Sub Main - Console.WriteLine(String.Format(New TelephoneFormatter, "{0}", 0)) - Console.WriteLine(String.Format(New TelephoneFormatter, "{0}", 911)) - Console.WriteLine(String.Format(New TelephoneFormatter, "{0}", 8490216)) - ' - Console.WriteLine(String.Format(New TelephoneFormatter, "{0}", 4257884748)) - ' - - Console.WriteLine(String.Format(New TelephoneFormatter, "{0:N}", 0)) - Console.WriteLine(String.Format(New TelephoneFormatter, "{0:N}", 911)) - Console.WriteLine(String.Format(New TelephoneFormatter, "{0:N}", 8490216)) - ' - Console.WriteLine(String.Format(New TelephoneFormatter, "{0:N}", 4257884748)) - ' + Public Sub Main + Console.WriteLine(String.Format(New TelephoneFormatter, "{0}", 0)) + Console.WriteLine(String.Format(New TelephoneFormatter, "{0}", 911)) + Console.WriteLine(String.Format(New TelephoneFormatter, "{0}", 8490216)) + ' + Console.WriteLine(String.Format(New TelephoneFormatter, "{0}", 4257884748)) + ' + + Console.WriteLine(String.Format(New TelephoneFormatter, "{0:N}", 0)) + Console.WriteLine(String.Format(New TelephoneFormatter, "{0:N}", 911)) + Console.WriteLine(String.Format(New TelephoneFormatter, "{0:N}", 8490216)) + ' + Console.WriteLine(String.Format(New TelephoneFormatter, "{0:N}", 4257884748)) + ' - Console.WriteLine(String.Format(New TelephoneFormatter, "{0:I}", 4257884748)) - End Sub + Console.WriteLine(String.Format(New TelephoneFormatter, "{0:I}", 4257884748)) + End Sub End Module ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.PadNumber/vb/Pad1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.PadNumber/vb/Pad1.vb index 2ce17999cd327..7ae8a82bb0013 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.PadNumber/vb/Pad1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.PadNumber/vb/Pad1.vb @@ -4,124 +4,124 @@ Option Strict On Imports System.Globalization Module Example - Public Sub Main() - PadInteger() - Console.WriteLine("-----") - PadIntegerWithNZeroes() - Console.WriteLine("-----") - PadNumber() - Console.WriteLine("-----") - PadNumberWithNZeroes() - End Sub - - Private Sub PadInteger() - ' - Dim byteValue As Byte = 254 - Dim shortValue As Short = 10342 - Dim intValue As Integer = 1023983 - Dim lngValue As Long = 6985321 - Dim ulngValue As ULong = UInt64.MaxValue - - ' Display integer values by calling the ToString method. - Console.WriteLine("{0,22} {1,22}", byteValue.ToString("D8"), byteValue.ToString("X8")) - Console.WriteLine("{0,22} {1,22}", shortValue.ToString("D8"), shortValue.ToString("X8")) - Console.WriteLine("{0,22} {1,22}", intValue.ToString("D8"), intValue.ToString("X8")) - Console.WriteLine("{0,22} {1,22}", lngValue.ToString("D8"), lngValue.ToString("X8")) - Console.WriteLine("{0,22} {1,22}", ulngValue.ToString("D8"), ulngValue.ToString("X8")) - Console.WriteLine() - - ' Display the same integer values by using composite formatting. - Console.WriteLine("{0,22:D8} {0,22:X8}", byteValue) - Console.WriteLine("{0,22:D8} {0,22:X8}", shortValue) - Console.WriteLine("{0,22:D8} {0,22:X8}", intValue) - Console.WriteLine("{0,22:D8} {0,22:X8}", lngValue) - Console.WriteLine("{0,22:D8} {0,22:X8}", ulngValue) - ' The example displays the following output: - ' 00000254 000000FE - ' 00010342 00002866 - ' 01023983 000F9FEF - ' 06985321 006A9669 - ' 18446744073709551615 FFFFFFFFFFFFFFFF - ' - ' 00000254 000000FE - ' 00010342 00002866 - ' 01023983 000F9FEF - ' 06985321 006A9669 - ' 18446744073709551615 FFFFFFFFFFFFFFFF + Public Sub Main() + PadInteger() + Console.WriteLine("-----") + PadIntegerWithNZeroes() + Console.WriteLine("-----") + PadNumber() + Console.WriteLine("-----") + PadNumberWithNZeroes() + End Sub + + Private Sub PadInteger() + ' + Dim byteValue As Byte = 254 + Dim shortValue As Short = 10342 + Dim intValue As Integer = 1023983 + Dim lngValue As Long = 6985321 + Dim ulngValue As ULong = UInt64.MaxValue + + ' Display integer values by calling the ToString method. + Console.WriteLine("{0,22} {1,22}", byteValue.ToString("D8"), byteValue.ToString("X8")) + Console.WriteLine("{0,22} {1,22}", shortValue.ToString("D8"), shortValue.ToString("X8")) + Console.WriteLine("{0,22} {1,22}", intValue.ToString("D8"), intValue.ToString("X8")) + Console.WriteLine("{0,22} {1,22}", lngValue.ToString("D8"), lngValue.ToString("X8")) + Console.WriteLine("{0,22} {1,22}", ulngValue.ToString("D8"), ulngValue.ToString("X8")) + Console.WriteLine() + + ' Display the same integer values by using composite formatting. + Console.WriteLine("{0,22:D8} {0,22:X8}", byteValue) + Console.WriteLine("{0,22:D8} {0,22:X8}", shortValue) + Console.WriteLine("{0,22:D8} {0,22:X8}", intValue) + Console.WriteLine("{0,22:D8} {0,22:X8}", lngValue) + Console.WriteLine("{0,22:D8} {0,22:X8}", ulngValue) + ' The example displays the following output: + ' 00000254 000000FE + ' 00010342 00002866 + ' 01023983 000F9FEF + ' 06985321 006A9669 + ' 18446744073709551615 FFFFFFFFFFFFFFFF + ' + ' 00000254 000000FE + ' 00010342 00002866 + ' 01023983 000F9FEF + ' 06985321 006A9669 + ' 18446744073709551615 FFFFFFFFFFFFFFFF ' - End Sub - - Private Sub PadIntegerWithNZeroes() - ' - Dim value As Integer = 160934 - Dim decimalLength As Integer = value.ToString("D").Length + 5 - Dim hexLength As Integer = value.ToString("X").Length + 5 - Console.WriteLine(value.ToString("D" + decimalLength.ToString())) - Console.WriteLine(value.ToString("X" + hexLength.ToString())) - ' The example displays the following output: - ' 00000160934 - ' 00000274A6 - ' - End Sub + End Sub + + Private Sub PadIntegerWithNZeroes() + ' + Dim value As Integer = 160934 + Dim decimalLength As Integer = value.ToString("D").Length + 5 + Dim hexLength As Integer = value.ToString("X").Length + 5 + Console.WriteLine(value.ToString("D" + decimalLength.ToString())) + Console.WriteLine(value.ToString("X" + hexLength.ToString())) + ' The example displays the following output: + ' 00000160934 + ' 00000274A6 + ' + End Sub + + Private Sub PadNumber() + ' + Dim fmt As String = "00000000.##" + Dim intValue As Integer = 1053240 + Dim decValue As Decimal = 103932.52d + Dim sngValue As Single = 1549230.10873992 + Dim dblValue As Double = 9034521202.93217412 + + ' Display the numbers using the ToString method. + Console.WriteLine(intValue.ToString(fmt)) + Console.WriteLine(decValue.ToString(fmt)) + Console.WriteLine(sngValue.ToString(fmt)) + Console.WriteLine(dblValue.ToString(fmt)) + Console.WriteLine() + + ' Display the numbers using composite formatting. + Dim formatString As String = " {0,15:" + fmt + "}" + Console.WriteLine(formatString, intValue) + Console.WriteLine(formatString, decValue) + Console.WriteLine(formatString, sngValue) + Console.WriteLine(formatString, dblValue) + ' The example displays the following output: + ' 01053240 + ' 00103932.52 + ' 01549230 + ' 9034521202.93 + ' + ' 01053240 + ' 00103932.52 + ' 01549230 + ' 9034521202.93 + ' + End Sub + + Private Sub PadNumberWithNZeroes() + ' + Dim dblValues() As Double = {9034521202.93217412, 9034521202} + For Each dblValue As Double In dblValues + Dim decSeparator As String = System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + Dim fmt, formatString As String - Private Sub PadNumber() - ' - Dim fmt As String = "00000000.##" - Dim intValue As Integer = 1053240 - Dim decValue As Decimal = 103932.52d - Dim sngValue As Single = 1549230.10873992 - Dim dblValue As Double = 9034521202.93217412 - - ' Display the numbers using the ToString method. - Console.WriteLine(intValue.ToString(fmt)) - Console.WriteLine(decValue.ToString(fmt)) - Console.WriteLine(sngValue.ToString(fmt)) - Console.WriteLine(dblValue.ToString(fmt)) - Console.WriteLine() - - ' Display the numbers using composite formatting. - Dim formatString As String = " {0,15:" + fmt + "}" - Console.WriteLine(formatString, intValue) - Console.WriteLine(formatString, decValue) - Console.WriteLine(formatString, sngValue) - Console.WriteLine(formatString, dblValue) - ' The example displays the following output: - ' 01053240 - ' 00103932.52 - ' 01549230 - ' 9034521202.93 - ' - ' 01053240 - ' 00103932.52 - ' 01549230 - ' 9034521202.93 - ' - End Sub - - Private Sub PadNumberWithNZeroes() - ' - Dim dblValues() As Double = { 9034521202.93217412, 9034521202 } - For Each dblValue As Double In dblValues - Dim decSeparator As String = System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator - Dim fmt, formatString As String - - If dblValue.ToString.Contains(decSeparator) Then - Dim digits As Integer = dblValue.ToString().IndexOf(decSeparator) - fmt = New String("0"c, 5) + New String("#"c, digits) + ".##" - Else - fmt = New String("0"c, dblValue.ToString.Length) - End If - formatString = "{0,20:" + fmt + "}" + If dblValue.ToString.Contains(decSeparator) Then + Dim digits As Integer = dblValue.ToString().IndexOf(decSeparator) + fmt = New String("0"c, 5) + New String("#"c, digits) + ".##" + Else + fmt = New String("0"c, dblValue.ToString.Length) + End If + formatString = "{0,20:" + fmt + "}" - Console.WriteLine(dblValue.ToString(fmt)) - Console.WriteLine(formatString, dblValue) - Next - ' The example displays the following output: - ' 000009034521202.93 - ' 000009034521202.93 - ' 9034521202 - ' 9034521202 - ' - End Sub + Console.WriteLine(dblValue.ToString(fmt)) + Console.WriteLine(formatString, dblValue) + Next + ' The example displays the following output: + ' 000009034521202.93 + ' 000009034521202.93 + ' 9034521202 + ' 9034521202 + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.RoundTrip/vb/RoundTrip.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.RoundTrip/vb/RoundTrip.vb index 894f4393687b4..43ad84cea9cd7 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.RoundTrip/vb/RoundTrip.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.RoundTrip/vb/RoundTrip.vb @@ -8,159 +8,159 @@ Imports System.Runtime.Serialization.Formatters.Binary Module modMain - Public Sub Main() - RoundTripDateTime() - Console.WriteLine() - RoundTripDateTimeOffset() - Console.WriteLine() - RoundTripTimeWithTimeZone() - End Sub - - Private Sub RoundTripDateTime() - ' - Const fileName As String = ".\DateFile.txt" - - Dim outFile As New StreamWriter(fileName) - - ' Save DateTime value. - Dim dateToSave As Date = DateTime.SpecifyKind(#06/12/2008 6:45:15 PM#, _ - DateTimeKind.Local) - Dim dateString As String = dateToSave.ToString("o") - Console.WriteLine("Converted {0} ({1}) to {2}.", dateToSave.ToString(), _ - dateToSave.Kind.ToString(), dateString) - outFile.WriteLine(dateString) - Console.WriteLine("Wrote {0} to {1}.", dateString, fileName) - outFile.Close() - - ' Restore DateTime value. - Dim restoredDate As Date - - Dim inFile As New StreamReader(fileName) - dateString = inFile.ReadLine() - inFile.Close() - restoredDate = DateTime.Parse(dateString, Nothing, DateTimeStyles.RoundTripKind) - Console.WriteLine("Read {0} ({2}) from {1}.", restoredDate.ToString(), _ - fileName, restoredDAte.Kind.ToString()) - ' The example displays the following output: - ' Converted 6/12/2008 6:45:15 PM (Local) to 2008-06-12T18:45:15.0000000-05:00. - ' Wrote 2008-06-12T18:45:15.0000000-05:00 to .\DateFile.txt. - ' Read 6/12/2008 6:45:15 PM (Local) from .\DateFile.txt. - ' - End Sub - - Private Sub RoundTripDateTimeOffset() - ' - Const fileName As String = ".\DateOff.txt" - - Dim outFile As New StreamWriter(fileName) - - ' Save DateTime value. - Dim dateToSave As New DateTimeOffset(2008, 6, 12, 18, 45, 15, _ - New TimeSpan(7, 0, 0)) - Dim dateString As String = dateToSave.ToString("o") - Console.WriteLine("Converted {0} to {1}.", dateToSave.ToString(), dateString) - outFile.WriteLine(dateString) - Console.WriteLine("Wrote {0} to {1}.", dateString, fileName) - outFile.Close() - - ' Restore DateTime value. - Dim restoredDateOff As DateTimeOffset - - Dim inFile As New StreamReader(fileName) - dateString = inFile.ReadLine() - inFile.Close() - restoredDateOff = DateTimeOffset.Parse(dateString, Nothing, DateTimeStyles.RoundTripKind) - Console.WriteLine("Read {0} from {1}.", restoredDateOff.ToString(), fileName) - ' The example displays the following output: - ' Converted 6/12/2008 6:45:15 PM +07:00 to 2008-06-12T18:45:15.0000000+07:00. - ' Wrote 2008-06-12T18:45:15.0000000+07:00 to .\DateOff.txt. - ' Read 6/12/2008 6:45:15 PM +07:00 from .\DateOff.txt. - ' - End Sub - - Private Sub RoundTripTimeWithTimeZone() - ' - Const fileName As String = ".\DateWithTz.dat" - - Dim tempDate As Date = #9/3/2008 7:00:00 PM# - Dim tempTz As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time") - Dim dateWithTz As New DateInTimeZone(New DateTimeOffset(tempDate, _ - tempTz.GetUtcOffset(tempDate)), _ - tempTz) - - ' Store DateInTimeZone value to a file - Dim outFile As New FileStream(fileName, FileMode.Create) - Try - Dim formatter As New BinaryFormatter() - formatter.Serialize(outFile, dateWithTz) - Console.WriteLine("Saving {0} {1} to {2}", dateWithTz.DateAndTime, _ - IIf(dateWithTz.TimeZone.IsDaylightSavingTime(dateWithTz.DateAndTime), _ - dateWithTz.TimeZone.DaylightName, dateWithTz.TimeZone.DaylightName), _ - fileName) - Catch e As SerializationException - Console.WriteLine("Unable to serialize time data to {0}.", fileName) - Finally - outFile.Close() - End Try - - ' Retrieve DateInTimeZone value - If File.Exists(fileName) Then - Dim inFile As New FileStream(fileName, FileMode.Open) - Dim dateWithTz2 As New DateInTimeZone() - Try + Public Sub Main() + RoundTripDateTime() + Console.WriteLine() + RoundTripDateTimeOffset() + Console.WriteLine() + RoundTripTimeWithTimeZone() + End Sub + + Private Sub RoundTripDateTime() + ' + Const fileName As String = ".\DateFile.txt" + + Dim outFile As New StreamWriter(fileName) + + ' Save DateTime value. + Dim dateToSave As Date = DateTime.SpecifyKind(#06/12/2008 6:45:15 PM#, _ + DateTimeKind.Local) + Dim dateString As String = dateToSave.ToString("o") + Console.WriteLine("Converted {0} ({1}) to {2}.", dateToSave.ToString(), _ + dateToSave.Kind.ToString(), dateString) + outFile.WriteLine(dateString) + Console.WriteLine("Wrote {0} to {1}.", dateString, fileName) + outFile.Close() + + ' Restore DateTime value. + Dim restoredDate As Date + + Dim inFile As New StreamReader(fileName) + dateString = inFile.ReadLine() + inFile.Close() + restoredDate = DateTime.Parse(dateString, Nothing, DateTimeStyles.RoundTripKind) + Console.WriteLine("Read {0} ({2}) from {1}.", restoredDate.ToString(), _ + fileName, restoredDAte.Kind.ToString()) + ' The example displays the following output: + ' Converted 6/12/2008 6:45:15 PM (Local) to 2008-06-12T18:45:15.0000000-05:00. + ' Wrote 2008-06-12T18:45:15.0000000-05:00 to .\DateFile.txt. + ' Read 6/12/2008 6:45:15 PM (Local) from .\DateFile.txt. + ' + End Sub + + Private Sub RoundTripDateTimeOffset() + ' + Const fileName As String = ".\DateOff.txt" + + Dim outFile As New StreamWriter(fileName) + + ' Save DateTime value. + Dim dateToSave As New DateTimeOffset(2008, 6, 12, 18, 45, 15, _ + New TimeSpan(7, 0, 0)) + Dim dateString As String = dateToSave.ToString("o") + Console.WriteLine("Converted {0} to {1}.", dateToSave.ToString(), dateString) + outFile.WriteLine(dateString) + Console.WriteLine("Wrote {0} to {1}.", dateString, fileName) + outFile.Close() + + ' Restore DateTime value. + Dim restoredDateOff As DateTimeOffset + + Dim inFile As New StreamReader(fileName) + dateString = inFile.ReadLine() + inFile.Close() + restoredDateOff = DateTimeOffset.Parse(dateString, Nothing, DateTimeStyles.RoundTripKind) + Console.WriteLine("Read {0} from {1}.", restoredDateOff.ToString(), fileName) + ' The example displays the following output: + ' Converted 6/12/2008 6:45:15 PM +07:00 to 2008-06-12T18:45:15.0000000+07:00. + ' Wrote 2008-06-12T18:45:15.0000000+07:00 to .\DateOff.txt. + ' Read 6/12/2008 6:45:15 PM +07:00 from .\DateOff.txt. + ' + End Sub + + Private Sub RoundTripTimeWithTimeZone() + ' + Const fileName As String = ".\DateWithTz.dat" + + Dim tempDate As Date = #9/3/2008 7:00:00 PM# + Dim tempTz As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time") + Dim dateWithTz As New DateInTimeZone(New DateTimeOffset(tempDate, _ + tempTz.GetUtcOffset(tempDate)), _ + tempTz) + + ' Store DateInTimeZone value to a file + Dim outFile As New FileStream(fileName, FileMode.Create) + Try Dim formatter As New BinaryFormatter() - dateWithTz2 = DirectCast(formatter.Deserialize(inFile), DateInTimeZone) - Console.WriteLine("Restored {0} {1} from {2}", dateWithTz2.DateAndTime, _ - IIf(dateWithTz2.TimeZone.IsDaylightSavingTime(dateWithTz2.DateAndTime), _ - dateWithTz2.TimeZone.DaylightName, dateWithTz2.TimeZone.DaylightName), _ - fileName) - Catch e As SerializationException - Console.WriteLine("Unable to retrieve date and time information from {0}", _ - fileName) - Finally - inFile.Close - End Try - End If - ' This example displays the following output to the console: - ' Saving 9/3/2008 7:00:00 PM -05:00 Central Daylight Time to .\DateWithTz.dat - ' Restored 9/3/2008 7:00:00 PM -05:00 Central Daylight Time from .\DateWithTz.dat - ' - End Sub + formatter.Serialize(outFile, dateWithTz) + Console.WriteLine("Saving {0} {1} to {2}", dateWithTz.DateAndTime, _ + IIf(dateWithTz.TimeZone.IsDaylightSavingTime(dateWithTz.DateAndTime), _ + dateWithTz.TimeZone.DaylightName, dateWithTz.TimeZone.DaylightName), _ + fileName) + Catch e As SerializationException + Console.WriteLine("Unable to serialize time data to {0}.", fileName) + Finally + outFile.Close() + End Try + + ' Retrieve DateInTimeZone value + If File.Exists(fileName) Then + Dim inFile As New FileStream(fileName, FileMode.Open) + Dim dateWithTz2 As New DateInTimeZone() + Try + Dim formatter As New BinaryFormatter() + dateWithTz2 = DirectCast(formatter.Deserialize(inFile), DateInTimeZone) + Console.WriteLine("Restored {0} {1} from {2}", dateWithTz2.DateAndTime, _ + IIf(dateWithTz2.TimeZone.IsDaylightSavingTime(dateWithTz2.DateAndTime), _ + dateWithTz2.TimeZone.DaylightName, dateWithTz2.TimeZone.DaylightName), _ + fileName) + Catch e As SerializationException + Console.WriteLine("Unable to retrieve date and time information from {0}", _ + fileName) + Finally + inFile.Close + End Try + End If + ' This example displays the following output to the console: + ' Saving 9/3/2008 7:00:00 PM -05:00 Central Daylight Time to .\DateWithTz.dat + ' Restored 9/3/2008 7:00:00 PM -05:00 Central Daylight Time from .\DateWithTz.dat + ' + End Sub End Module ' Public Class DateInTimeZone - Private tz As TimeZoneInfo - Private thisDate As DateTimeOffset - - Public Sub New() - End Sub - - Public Sub New(date1 As DateTimeOffset, timeZone As TimeZoneInfo) - If timeZone Is Nothing Then - Throw New ArgumentNullException("The time zone cannot be null.") - End If - Me.thisDate = date1 - Me.tz = timeZone - End Sub - - Public Property DateAndTime As DateTimeOffset - Get - Return Me.thisDate - End Get - Set - If Value.Offset <> Me.tz.GetUtcOffset(Value) Then - Me.thisDate = TimeZoneInfo.ConvertTime(Value, tz) - Else - Me.thisDate = Value - End If - End Set - End Property - - Public ReadOnly Property TimeZone As TimeZoneInfo - Get - Return tz - End Get - End Property + Private tz As TimeZoneInfo + Private thisDate As DateTimeOffset + + Public Sub New() + End Sub + + Public Sub New(date1 As DateTimeOffset, timeZone As TimeZoneInfo) + If timeZone Is Nothing Then + Throw New ArgumentNullException("The time zone cannot be null.") + End If + Me.thisDate = date1 + Me.tz = timeZone + End Sub + + Public Property DateAndTime As DateTimeOffset + Get + Return Me.thisDate + End Get + Set + If Value.Offset <> Me.tz.GetUtcOffset(Value) Then + Me.thisDate = TimeZoneInfo.ConvertTime(Value, tz) + Else + Me.thisDate = Value + End If + End Set + End Property + + Public ReadOnly Property TimeZone As TimeZoneInfo + Get + Return tz + End Get + End Property End Class ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/Howto1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/Howto1.vb index 067533774bc43..b85bd8347b083 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/Howto1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/Howto1.vb @@ -6,31 +6,31 @@ Imports System.Globalization Imports System.Threading Module Example - Public Sub Main() - ' Change current culture to fr-FR - Dim originalCulture As CultureInfo = Thread.CurrentThread.CurrentCulture - Thread.CurrentThread.CurrentCulture = New CultureInfo("fr-FR") + Public Sub Main() + ' Change current culture to fr-FR + Dim originalCulture As CultureInfo = Thread.CurrentThread.CurrentCulture + Thread.CurrentThread.CurrentCulture = New CultureInfo("fr-FR") - Dim dateValue As Date = #6/11/2008# - ' Display the DayOfWeek string representation - Console.WriteLine(dateValue.DayOfWeek.ToString()) - ' Restore original current culture - Thread.CurrentThread.CurrentCulture = originalCulture - End Sub + Dim dateValue As Date = #6/11/2008# + ' Display the DayOfWeek string representation + Console.WriteLine(dateValue.DayOfWeek.ToString()) + ' Restore original current culture + Thread.CurrentThread.CurrentCulture = originalCulture + End Sub End Module ' The example displays the following output: ' Wednesday ' Public Class Example2 - Private Sub ShowAbbreviatedWithDateTimeInfo() - ' - Dim dateValue As Date = #6/11/2008# - Dim dateFormats As DateTimeFormatInfo = _ - New CultureInfo("es-ES").DateTimeFormat - Console.WriteLine(dateValue.ToString("ddd", _ - dateFormats)) ' Displays mer. - ' - End Sub + Private Sub ShowAbbreviatedWithDateTimeInfo() + ' + Dim dateValue As Date = #6/11/2008# + Dim dateFormats As DateTimeFormatInfo = _ + New CultureInfo("es-ES").DateTimeFormat + Console.WriteLine(dateValue.ToString("ddd", _ + dateFormats)) ' Displays mer. + ' + End Sub End Class diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/abbrname1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/abbrname1.vb index af8cc21972e10..660f1399ead97 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/abbrname1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/abbrname1.vb @@ -3,10 +3,10 @@ Option Strict On ' Module Example - Public Sub Main() - Dim dateValue As Date = #6/11/2008# - Console.WriteLine(dateValue.ToString("ddd")) - End Sub + Public Sub Main() + Dim dateValue As Date = #6/11/2008# + Console.WriteLine(dateValue.ToString("ddd")) + End Sub End Module ' The example displays the following output: ' Wed diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/abbrname2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/abbrname2.vb index b1ab0b4f75630..4898a6eb81d0c 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/abbrname2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/abbrname2.vb @@ -5,11 +5,11 @@ Option Strict On Imports System.Globalization Module Example - Public Sub Main() - Dim dateValue As Date = #6/11/2008# - Console.WriteLine(dateValue.ToString("ddd", - New CultureInfo("fr-FR"))) - End Sub + Public Sub Main() + Dim dateValue As Date = #6/11/2008# + Console.WriteLine(dateValue.ToString("ddd", + New CultureInfo("fr-FR"))) + End Sub End Module ' The example displays the following output: ' mer. diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/example6.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/example6.vb index bda6d0038027b..41b423adf2fa2 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/example6.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/example6.vb @@ -5,52 +5,52 @@ Option Strict On Imports System.Globalization Module Example - Public Sub Main() - Dim dateString As String = "6/11/2007" - Dim dateValue As Date - Dim dateOffsetValue As DateTimeOffset - - Try - Dim dateTimeFormats As DateTimeFormatInfo - ' Convert date representation to a date value - dateValue = Date.Parse(dateString, CultureInfo.InvariantCulture) - dateOffsetValue = New DateTimeOffset(dateValue, _ - TimeZoneInfo.Local.GetUtcOffset(dateValue)) - ' Convert date representation to a number indicating the day of week - Console.WriteLine(dateValue.DayOfWeek) - Console.WriteLine(dateOffsetValue.DayOfWeek) - - ' Display abbreviated weekday name using current culture - Console.WriteLine(dateValue.ToString("ddd")) - Console.WriteLine(dateOffsetValue.ToString("ddd")) - - ' Display full weekday name using current culture - Console.WriteLine(dateValue.ToString("dddd")) - Console.WriteLine(dateOffsetValue.ToString("dddd")) - - ' Display abbreviated weekday name for de-DE culture - Console.WriteLine(dateValue.ToString("ddd", New CultureInfo("de-DE"))) - Console.WriteLine(dateOffsetValue.ToString("ddd", _ - New CultureInfo("de-DE"))) + Public Sub Main() + Dim dateString As String = "6/11/2007" + Dim dateValue As Date + Dim dateOffsetValue As DateTimeOffset - ' Display abbreviated weekday name with de-DE DateTimeFormatInfo object - dateTimeFormats = New CultureInfo("de-DE").DateTimeFormat - Console.WriteLine(dateValue.ToString("ddd", dateTimeFormats)) - Console.WriteLine(dateOffsetValue.ToString("ddd", dateTimeFormats)) - - ' Display full weekday name for fr-FR culture - Console.WriteLine(dateValue.ToString("ddd", New CultureInfo("fr-FR"))) - Console.WriteLine(dateOffsetValue.ToString("ddd", _ - New CultureInfo("fr-FR"))) - - ' Display abbreviated weekday name with fr-FR DateTimeFormatInfo object - dateTimeFormats = New CultureInfo("fr-FR").DateTimeFormat - Console.WriteLine(dateValue.ToString("dddd", dateTimeFormats)) - Console.WriteLine(dateOffsetValue.ToString("dddd", dateTimeFormats)) - Catch e As FormatException - Console.WriteLine("Unable to convert {0} to a date.", dateString) - End Try - End Sub + Try + Dim dateTimeFormats As DateTimeFormatInfo + ' Convert date representation to a date value + dateValue = Date.Parse(dateString, CultureInfo.InvariantCulture) + dateOffsetValue = New DateTimeOffset(dateValue, _ + TimeZoneInfo.Local.GetUtcOffset(dateValue)) + ' Convert date representation to a number indicating the day of week + Console.WriteLine(dateValue.DayOfWeek) + Console.WriteLine(dateOffsetValue.DayOfWeek) + + ' Display abbreviated weekday name using current culture + Console.WriteLine(dateValue.ToString("ddd")) + Console.WriteLine(dateOffsetValue.ToString("ddd")) + + ' Display full weekday name using current culture + Console.WriteLine(dateValue.ToString("dddd")) + Console.WriteLine(dateOffsetValue.ToString("dddd")) + + ' Display abbreviated weekday name for de-DE culture + Console.WriteLine(dateValue.ToString("ddd", New CultureInfo("de-DE"))) + Console.WriteLine(dateOffsetValue.ToString("ddd", _ + New CultureInfo("de-DE"))) + + ' Display abbreviated weekday name with de-DE DateTimeFormatInfo object + dateTimeFormats = New CultureInfo("de-DE").DateTimeFormat + Console.WriteLine(dateValue.ToString("ddd", dateTimeFormats)) + Console.WriteLine(dateOffsetValue.ToString("ddd", dateTimeFormats)) + + ' Display full weekday name for fr-FR culture + Console.WriteLine(dateValue.ToString("ddd", New CultureInfo("fr-FR"))) + Console.WriteLine(dateOffsetValue.ToString("ddd", _ + New CultureInfo("fr-FR"))) + + ' Display abbreviated weekday name with fr-FR DateTimeFormatInfo object + dateTimeFormats = New CultureInfo("fr-FR").DateTimeFormat + Console.WriteLine(dateValue.ToString("dddd", dateTimeFormats)) + Console.WriteLine(dateOffsetValue.ToString("dddd", dateTimeFormats)) + Catch e As FormatException + Console.WriteLine("Unable to convert {0} to a date.", dateString) + End Try + End Sub End Module ' The example displays the following output to the console: ' 1 diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/example9.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/example9.vb index e999fe7949c24..00973fdaf2ed2 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/example9.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/example9.vb @@ -6,26 +6,26 @@ Imports System.Globalization Imports System.Threading Module Example - Public Sub Main() - Dim dateValue As Date = #6/11/2008# - - ' Get weekday number using Visual Basic Weekday function - Console.WriteLine(Weekday(dateValue)) ' Displays 4 - ' Compare with .NET DateTime.DayOfWeek property - Console.WriteLine(dateValue.DayOfWeek) ' Displays 3 - - ' Get weekday name using Weekday and WeekdayName functions - Console.WriteLine(WeekdayName(Weekday(dateValue))) ' Displays Wednesday - - ' Change culture to de-DE - Dim originalCulture As CultureInfo = Thread.CurrentThread.CurrentCulture - Thread.CurrentThread.CurrentCulture = New CultureInfo("de-DE") - ' Get weekday name using Weekday and WeekdayName functions - Console.WriteLine(WeekdayName(Weekday(dateValue))) ' Displays Donnerstag - - ' Restore original culture - Thread.CurrentThread.CurrentCulture = originalCulture - End Sub + Public Sub Main() + Dim dateValue As Date = #6/11/2008# + + ' Get weekday number using Visual Basic Weekday function + Console.WriteLine(Weekday(dateValue)) ' Displays 4 + ' Compare with .NET DateTime.DayOfWeek property + Console.WriteLine(dateValue.DayOfWeek) ' Displays 3 + + ' Get weekday name using Weekday and WeekdayName functions + Console.WriteLine(WeekdayName(Weekday(dateValue))) ' Displays Wednesday + + ' Change culture to de-DE + Dim originalCulture As CultureInfo = Thread.CurrentThread.CurrentCulture + Thread.CurrentThread.CurrentCulture = New CultureInfo("de-DE") + ' Get weekday name using Weekday and WeekdayName functions + Console.WriteLine(WeekdayName(Weekday(dateValue))) ' Displays Donnerstag + + ' Restore original culture + Thread.CurrentThread.CurrentCulture = originalCulture + End Sub End Module ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/fullname4.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/fullname4.vb index c8ed101612d1a..55227d1234789 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/fullname4.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/fullname4.vb @@ -3,10 +3,10 @@ Option Strict On ' Module Example - Public Sub Main() - Dim dateValue As Date = #6/11/2008# - Console.WriteLine(dateValue.ToString("dddd")) - End Sub + Public Sub Main() + Dim dateValue As Date = #6/11/2008# + Console.WriteLine(dateValue.ToString("dddd")) + End Sub End Module ' The example displays the following output: ' Wednesday diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/fullname5.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/fullname5.vb index 7bd28caeda777..3a4f5a01989e8 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/fullname5.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/fullname5.vb @@ -5,11 +5,11 @@ Option Strict On Imports System.Globalization Module Example - Public Sub Main() - Dim dateValue As Date = #6/11/2008# - Console.WriteLine(dateValue.ToString("dddd", _ - New CultureInfo("es-ES"))) - End Sub + Public Sub Main() + Dim dateValue As Date = #6/11/2008# + Console.WriteLine(dateValue.ToString("dddd", _ + New CultureInfo("es-ES"))) + End Sub End Module ' The example displays the following output: ' miércoles. diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/weekdaynumber7.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/weekdaynumber7.vb index ad42d638f1a74..81bb464dc5c66 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/weekdaynumber7.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/vb/weekdaynumber7.vb @@ -3,10 +3,10 @@ Option Strict On ' Module Example - Public Sub Main() - Dim dateValue As Date = #6/11/2008# - Console.WriteLine(dateValue.DayOfWeek) - End Sub + Public Sub Main() + Dim dateValue As Date = #6/11/2008# + Console.WriteLine(dateValue.DayOfWeek) + End Sub End Module ' The example displays the following output: ' 3 diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/Standard.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/Standard.vb index 2cdf7c78bf78e..1d917991ae6e0 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/Standard.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/Standard.vb @@ -5,233 +5,233 @@ Imports System.Globalization Module modMain - Public Sub Main() - Console.Clear() - Console.WriteLine(CultureInfo.CurrentUICulture.Name) - Console.WriteLine(CultureInfo.CurrentCulture.Name) - Console.WriteLine() - Console.WriteLine("Currency Format Specifier:") - ShowCurrency() - Console.WriteLine() - Console.WriteLine("Decimal Format Specifier:") - ShowDecimal() - Console.WriteLine() - Console.WriteLine("Exponentiation Format Specifier:") - ShowExponentiation() - Console.WriteLine() - Console.WriteLine("Fixed Point Format Specifier:") - ShowFixedPoint() - Console.WriteLine() - Console.WriteLine("'G' Format Specifier:") - ShowGeneral() - Console.WriteLine() - Console.WriteLine("'N' Format Specifier:") - ShowNumeric() - Console.WriteLine() - Console.WriteLine("Percent Format Specifier:") - ShowPercent() - Console.WriteLine() - Console.WriteLine("Round-trip Format Specifier:") - ShowRoundTrip() - Console.WriteLine() - Console.WriteLine("Hexadecimal Format Specifier:") - ShowHex() - Console.WriteLine() - Console.WriteLine("Invalid Format Specifier") - ShowInvalid() - End Sub - - Private Sub ShowCurrency() - ' - Dim value As Double = 12345.6789 - Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture)) - - Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture)) - - Console.WriteLine(value.ToString("C3", _ - CultureInfo.CreateSpecificCulture("da-DK"))) - ' The example displays the following output on a system whose - ' current culture is English (United States): - ' $12,345.68 - ' $12,345.679 - ' kr 12.345,679 - ' - End Sub - - Private Sub ShowDecimal() - ' - Dim value As Integer - - value = 12345 - Console.WriteLine(value.ToString("D")) - ' Displays 12345 - Console.WriteLine(value.ToString("D8")) - ' Displays 00012345 - - value = -12345 - Console.WriteLine(value.ToString("D")) - ' Displays -12345 - Console.WriteLine(value.ToString("D8")) - ' Displays -00012345 - ' - End Sub - - Private Sub ShowExponentiation() - ' - Dim value As Double = 12345.6789 - Console.WriteLine(value.ToString("E", CultureInfo.InvariantCulture)) - ' Displays 1.234568E+004 - - Console.WriteLine(value.ToString("E10", CultureInfo.InvariantCulture)) - ' Displays 1.2345678900E+004 - - Console.WriteLine(value.ToString("e4", CultureInfo.InvariantCulture)) - ' Displays 1.2346e+004 - - Console.WriteLine(value.ToString("E", _ - CultureInfo.CreateSpecificCulture("fr-FR"))) - ' Displays 1,234568E+004 - ' - End Sub - - Private Sub ShowFixedPoint() - ' - Dim integerNumber As Integer - integerNumber = 17843 - Console.WriteLine(integerNumber.ToString("F", CultureInfo.InvariantCulture)) - ' Displays 17843.00 - - integerNumber = -29541 - Console.WriteLine(integerNumber.ToString("F3", CultureInfo.InvariantCulture)) - ' Displays -29541.000 - - Dim doubleNumber As Double - doubleNumber = 18934.1879 - Console.WriteLine(doubleNumber.ToString("F", CultureInfo.InvariantCulture)) - ' Displays 18934.19 - - Console.WriteLine(doubleNumber.ToString("F0", CultureInfo.InvariantCulture)) - ' Displays 18934 - - doubleNumber = -1898300.1987 - Console.WriteLine(doubleNumber.ToString("F1", CultureInfo.InvariantCulture)) - ' Displays -1898300.2 - - Console.WriteLine(doubleNumber.ToString("F3", _ - CultureInfo.CreateSpecificCulture("es-ES"))) - ' Displays -1898300,199 - ' - End Sub - - Private Sub ShowGeneral() - ' - Dim number As Double - - number = 12345.6789 - Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture)) - ' Displays 12345.6789 - Console.WriteLine(number.ToString("G", _ - CultureInfo.CreateSpecificCulture("fr-FR"))) - ' Displays 12345,6789 - - Console.WriteLine(number.ToString("G7", CultureInfo.InvariantCulture)) - ' Displays 12345.68 - - number = .0000023 - Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture)) - ' Displays 2.3E-06 - Console.WriteLine(number.ToString("G", _ - CultureInfo.CreateSpecificCulture("fr-FR"))) - ' Displays 2,3E-06 - - number = .0023 - Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture)) - ' Displays 0.0023 - - number = 1234 - Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture)) - ' Displays 1.2E+03 - - number = Math.Pi - Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture)) - ' Displays 3.1416 - ' - End Sub - - Private Sub ShowNumeric() - ' - Dim dblValue As Double = -12445.6789 - Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture)) - ' Displays -12,445.68 - Console.WriteLine(dblValue.ToString("N1", _ - CultureInfo.CreateSpecificCulture("sv-SE"))) - ' Displays -12 445,7 - - Dim intValue As Integer = 123456789 - Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture)) - ' Displays 123,456,789.0 - ' - End Sub - - Private Sub ShowPercent() - ' - Dim number As Double = .2468013 - Console.WriteLine(number.ToString("P", CultureInfo.InvariantCulture)) - ' Displays 24.68 % - Console.WriteLine(number.ToString("P", _ - CultureInfo.CreateSpecificCulture("hr-HR"))) - ' Displays 24,68% - Console.WriteLine(number.ToString("P1", CultureInfo.InvariantCulture)) - ' Displays 24.7 % - ' - End Sub - - Private Sub ShowRoundTrip() - ' - Dim value As Double - - value = Math.Pi - Console.WriteLine(value.ToString("r")) - ' Displays 3.1415926535897931 - Console.WriteLine(value.ToString("r", _ - CultureInfo.CreateSpecificCulture("fr-FR"))) - ' Displays 3,1415926535897931 - value = 1.623e-21 - Console.WriteLine(value.ToString("r")) - ' Displays 1.623E-21 - ' - End Sub - - Private Sub ShowHex() - ' - Dim value As Integer - - value = &h2045e - Console.WriteLine(value.ToString("x")) - ' Displays 2045e - Console.WriteLine(value.ToString("X")) - ' Displays 2045E - Console.WriteLine(value.ToString("X8")) - ' Displays 0002045E - - value = 123456789 - Console.WriteLine(value.ToString("X")) - ' Displays 75BCD15 - Console.WriteLine(value.ToString("X2")) - ' Displays 75BCD15 - ' - End Sub - - Private Sub ShowInvalid() - Dim value As Integer = 12 - Dim specifier AS String = "Z" - Try - Console.WriteLine(value.ToString("Z")) - Catch e As Exception - Console.WriteLine("{0}: {1} is not a valid format specifier.", _ - e.GetType().Name, specifier) - End Try - End Sub + Public Sub Main() + Console.Clear() + Console.WriteLine(CultureInfo.CurrentUICulture.Name) + Console.WriteLine(CultureInfo.CurrentCulture.Name) + Console.WriteLine() + Console.WriteLine("Currency Format Specifier:") + ShowCurrency() + Console.WriteLine() + Console.WriteLine("Decimal Format Specifier:") + ShowDecimal() + Console.WriteLine() + Console.WriteLine("Exponentiation Format Specifier:") + ShowExponentiation() + Console.WriteLine() + Console.WriteLine("Fixed Point Format Specifier:") + ShowFixedPoint() + Console.WriteLine() + Console.WriteLine("'G' Format Specifier:") + ShowGeneral() + Console.WriteLine() + Console.WriteLine("'N' Format Specifier:") + ShowNumeric() + Console.WriteLine() + Console.WriteLine("Percent Format Specifier:") + ShowPercent() + Console.WriteLine() + Console.WriteLine("Round-trip Format Specifier:") + ShowRoundTrip() + Console.WriteLine() + Console.WriteLine("Hexadecimal Format Specifier:") + ShowHex() + Console.WriteLine() + Console.WriteLine("Invalid Format Specifier") + ShowInvalid() + End Sub + + Private Sub ShowCurrency() + ' + Dim value As Double = 12345.6789 + Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture)) + + Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture)) + + Console.WriteLine(value.ToString("C3", _ + CultureInfo.CreateSpecificCulture("da-DK"))) + ' The example displays the following output on a system whose + ' current culture is English (United States): + ' $12,345.68 + ' $12,345.679 + ' kr 12.345,679 + ' + End Sub + + Private Sub ShowDecimal() + ' + Dim value As Integer + + value = 12345 + Console.WriteLine(value.ToString("D")) + ' Displays 12345 + Console.WriteLine(value.ToString("D8")) + ' Displays 00012345 + + value = -12345 + Console.WriteLine(value.ToString("D")) + ' Displays -12345 + Console.WriteLine(value.ToString("D8")) + ' Displays -00012345 + ' + End Sub + + Private Sub ShowExponentiation() + ' + Dim value As Double = 12345.6789 + Console.WriteLine(value.ToString("E", CultureInfo.InvariantCulture)) + ' Displays 1.234568E+004 + + Console.WriteLine(value.ToString("E10", CultureInfo.InvariantCulture)) + ' Displays 1.2345678900E+004 + + Console.WriteLine(value.ToString("e4", CultureInfo.InvariantCulture)) + ' Displays 1.2346e+004 + + Console.WriteLine(value.ToString("E", _ + CultureInfo.CreateSpecificCulture("fr-FR"))) + ' Displays 1,234568E+004 + ' + End Sub + + Private Sub ShowFixedPoint() + ' + Dim integerNumber As Integer + integerNumber = 17843 + Console.WriteLine(integerNumber.ToString("F", CultureInfo.InvariantCulture)) + ' Displays 17843.00 + + integerNumber = -29541 + Console.WriteLine(integerNumber.ToString("F3", CultureInfo.InvariantCulture)) + ' Displays -29541.000 + + Dim doubleNumber As Double + doubleNumber = 18934.1879 + Console.WriteLine(doubleNumber.ToString("F", CultureInfo.InvariantCulture)) + ' Displays 18934.19 + + Console.WriteLine(doubleNumber.ToString("F0", CultureInfo.InvariantCulture)) + ' Displays 18934 + + doubleNumber = -1898300.1987 + Console.WriteLine(doubleNumber.ToString("F1", CultureInfo.InvariantCulture)) + ' Displays -1898300.2 + + Console.WriteLine(doubleNumber.ToString("F3", _ + CultureInfo.CreateSpecificCulture("es-ES"))) + ' Displays -1898300,199 + ' + End Sub + + Private Sub ShowGeneral() + ' + Dim number As Double + + number = 12345.6789 + Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture)) + ' Displays 12345.6789 + Console.WriteLine(number.ToString("G", _ + CultureInfo.CreateSpecificCulture("fr-FR"))) + ' Displays 12345,6789 + + Console.WriteLine(number.ToString("G7", CultureInfo.InvariantCulture)) + ' Displays 12345.68 + + number = .0000023 + Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture)) + ' Displays 2.3E-06 + Console.WriteLine(number.ToString("G", _ + CultureInfo.CreateSpecificCulture("fr-FR"))) + ' Displays 2,3E-06 + + number = .0023 + Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture)) + ' Displays 0.0023 + + number = 1234 + Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture)) + ' Displays 1.2E+03 + + number = Math.Pi + Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture)) + ' Displays 3.1416 + ' + End Sub + + Private Sub ShowNumeric() + ' + Dim dblValue As Double = -12445.6789 + Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture)) + ' Displays -12,445.68 + Console.WriteLine(dblValue.ToString("N1", _ + CultureInfo.CreateSpecificCulture("sv-SE"))) + ' Displays -12 445,7 + + Dim intValue As Integer = 123456789 + Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture)) + ' Displays 123,456,789.0 + ' + End Sub + + Private Sub ShowPercent() + ' + Dim number As Double = .2468013 + Console.WriteLine(number.ToString("P", CultureInfo.InvariantCulture)) + ' Displays 24.68 % + Console.WriteLine(number.ToString("P", _ + CultureInfo.CreateSpecificCulture("hr-HR"))) + ' Displays 24,68% + Console.WriteLine(number.ToString("P1", CultureInfo.InvariantCulture)) + ' Displays 24.7 % + ' + End Sub + + Private Sub ShowRoundTrip() + ' + Dim value As Double + + value = Math.Pi + Console.WriteLine(value.ToString("r")) + ' Displays 3.1415926535897931 + Console.WriteLine(value.ToString("r", _ + CultureInfo.CreateSpecificCulture("fr-FR"))) + ' Displays 3,1415926535897931 + value = 1.623e-21 + Console.WriteLine(value.ToString("r")) + ' Displays 1.623E-21 + ' + End Sub + + Private Sub ShowHex() + ' + Dim value As Integer + + value = &h2045e + Console.WriteLine(value.ToString("x")) + ' Displays 2045e + Console.WriteLine(value.ToString("X")) + ' Displays 2045E + Console.WriteLine(value.ToString("X8")) + ' Displays 0002045E + + value = 123456789 + Console.WriteLine(value.ToString("X")) + ' Displays 75BCD15 + Console.WriteLine(value.ToString("X2")) + ' Displays 75BCD15 + ' + End Sub + + Private Sub ShowInvalid() + Dim value As Integer = 12 + Dim specifier AS String = "Z" + Try + Console.WriteLine(value.ToString("Z")) + Catch e As Exception + Console.WriteLine("{0}: {1} is not a valid format specifier.", _ + e.GetType().Name, specifier) + End Try + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/standardusage1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/standardusage1.vb index bc87c1fd6d8f0..8a920f87f6900 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/standardusage1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/standardusage1.vb @@ -2,38 +2,38 @@ Option Strict On Module Example - Public Sub Main() - ShowToString() - ShowComposite() - ShowCompositeWithAlignment() - End Sub - - Private Sub ShowToString() - ' - Dim value As Decimal = 123.456d - Console.WriteLine(value.ToString("C2")) - ' Displays $123.46 - ' - End Sub - - Private Sub ShowComposite() - ' - Dim value As Decimal = 123.456d - Console.WriteLine("Your account balance is {0:C2}.", value) - ' Displays "Your account balance is $123.46." - ' - End Sub - - Private Sub ShowCompositeWithAlignment() - ' - Dim amounts() As Decimal = { 16305.32d, 18794.16d } - Console.WriteLine(" Beginning Balance Ending Balance") - Console.WriteLine(" {0,-28:C2}{1,14:C2}", amounts(0), amounts(1)) - ' Displays: - ' Beginning Balance Ending Balance - ' $16,305.32 $18,794.16 - ' - End Sub + Public Sub Main() + ShowToString() + ShowComposite() + ShowCompositeWithAlignment() + End Sub + + Private Sub ShowToString() + ' + Dim value As Decimal = 123.456d + Console.WriteLine(value.ToString("C2")) + ' Displays $123.46 + ' + End Sub + + Private Sub ShowComposite() + ' + Dim value As Decimal = 123.456d + Console.WriteLine("Your account balance is {0:C2}.", value) + ' Displays "Your account balance is $123.46." + ' + End Sub + + Private Sub ShowCompositeWithAlignment() + ' + Dim amounts() As Decimal = {16305.32d, 18794.16d} + Console.WriteLine(" Beginning Balance Ending Balance") + Console.WriteLine(" {0,-28:C2}{1,14:C2}", amounts(0), amounts(1)) + ' Displays: + ' Beginning Balance Ending Balance + ' $16,305.32 $18,794.16 + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb index 302c787e2ccd6..338ca3703e592 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb @@ -41,8 +41,8 @@ Class Program Try Dim lastCollCount As Integer = 0 Dim newCollCount As Integer = 0 - - + + While (True) If bAllocate = True Then @@ -65,7 +65,7 @@ Class Program End If End While - + Catch outofMem As OutOfMemoryException Console.WriteLine("Out of memory.") End Try diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/GenericMethodHowTo/VB/source.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/GenericMethodHowTo/VB/source.vb index 2a91227d35260..1081e63048aa6 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/GenericMethodHowTo/VB/source.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/GenericMethodHowTo/VB/source.vb @@ -35,7 +35,7 @@ Class GenericMethodBuilder Next Return retval - End Function + End Function ' @@ -78,7 +78,7 @@ Class GenericMethodBuilder ' Dim demoType As TypeBuilder = demoModule.DefineType( _ "DemoType", _ - TypeAttributes.Public) + TypeAttributes.Public) ' ' Define a Shared, Public method with standard calling @@ -132,14 +132,14 @@ Class GenericMethodBuilder ' Dim icoll As Type = GetType(ICollection(Of )) Dim icollOfTInput As Type = icoll.MakeGenericType(TInput) - Dim constraints() As Type = { icollOfTInput } + Dim constraints() As Type = {icollOfTInput} TOutput.SetInterfaceConstraints(constraints) ' ' Set parameter types for the method. The method takes ' one parameter, an array of type TInput. ' - Dim params() As Type = { TInput.MakeArrayType() } + Dim params() As Type = {TInput.MakeArrayType()} factory.SetParameters(params) ' @@ -291,7 +291,7 @@ Class GenericMethodBuilder ' one element in that array, the argument 'arr'. ' ' - Dim o As Object = bound.Invoke(Nothing, New Object() { arr }) + Dim o As Object = bound.Invoke(Nothing, New Object() {arr}) Dim list2 As List(Of String) = CType(o, List(Of String)) Console.WriteLine("The first element is: {0}", list2(0)) @@ -314,8 +314,8 @@ Class GenericMethodBuilder Console.WriteLine("The first element is: {0}", list3(0)) ' - End Sub -End Class + End Sub +End Class ' This code example produces the following output: ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb index d3827fed08af6..3cd97283f2af4 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb @@ -6,21 +6,21 @@ Imports System.Windows.Forms ' Class ExampleForm Inherits Form - - Public Sub New() + + Public Sub New() Me.Text = "Click me" - + End Sub End Class ' Class Example - Public Shared Sub Main() + Public Shared Sub Main() Dim ex As New Example() ex.HookUpDelegate() End Sub - - Private Sub HookUpDelegate() + + Private Sub HookUpDelegate() ' Load an assembly, for example using the Assembly.Load ' method. In this case, the executing assembly is loaded, to ' keep the demonstration simple. @@ -77,7 +77,7 @@ Class Example ' ' Dim miAddHandler As MethodInfo = evClick.GetAddMethod() - Dim addHandlerArgs() As Object = { d } + Dim addHandlerArgs() As Object = {d} miAddHandler.Invoke(exFormAsObj, addHandlerArgs) ' @@ -114,11 +114,11 @@ Class Example ' ' Dim ilgen As ILGenerator = handler.GetILGenerator() - - Dim showParameters As Type() = { GetType(String) } + + Dim showParameters As Type() = {GetType(String)} Dim simpleShow As MethodInfo = _ GetType(MessageBox).GetMethod("Show", showParameters) - + ilgen.Emit(OpCodes.Ldstr, _ "This event handler was constructed at run time.") ilgen.Emit(OpCodes.Call, simpleShow) @@ -132,7 +132,7 @@ Class Example ' ' Dim dEmitted As [Delegate] = handler.CreateDelegate(tDelegate) - miAddHandler.Invoke(exFormAsObj, New Object() { dEmitted }) + miAddHandler.Invoke(exFormAsObj, New Object() {dEmitted}) ' ' Show the form. Clicking on the form causes the two @@ -141,17 +141,17 @@ Class Example ' Application.Run(CType(exFormAsObj, Form)) ' - + End Sub - + Private Sub LuckyHandler(ByVal sender As [Object], _ - ByVal e As EventArgs) + ByVal e As EventArgs) MessageBox.Show("This event handler just happened to be lying around.") End Sub - + Private Function GetDelegateParameterTypes(ByVal d As Type) _ - As Type() + As Type() If d.BaseType IsNot GetType(MulticastDelegate) Then Throw New ApplicationException("Not a delegate.") @@ -171,11 +171,11 @@ Class Example Next i Return typeParameters - - End Function - - - Private Function GetDelegateReturnType(ByVal d As Type) As Type + + End Function + + + Private Function GetDelegateReturnType(ByVal d As Type) As Type If d.BaseType IsNot GetType(MulticastDelegate) Then Throw New ApplicationException("Not a delegate.") @@ -187,7 +187,7 @@ Class Example End If Return invoke.ReturnType - - End Function -End Class -' \ No newline at end of file + + End Function +End Class +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToDecryptXMLElementAsymmetric/vb/sample.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToDecryptXMLElementAsymmetric/vb/sample.vb index 87d48052ecda2..8ecd7d323a4fd 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToDecryptXMLElementAsymmetric/vb/sample.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToDecryptXMLElementAsymmetric/vb/sample.vb @@ -68,7 +68,7 @@ Module Program End If If KeyName Is Nothing Then Throw New ArgumentNullException("KeyName") - End If + End If ' ' Create a new EncryptedXml object. Dim exml As New EncryptedXml(Doc) @@ -86,4 +86,4 @@ Module Program End Sub End Module -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToDecryptXMLElementX509/vb/sample.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToDecryptXMLElementX509/vb/sample.vb index 3bc747b0f6ecf..b37cec0015975 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToDecryptXMLElementX509/vb/sample.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToDecryptXMLElementX509/vb/sample.vb @@ -53,4 +53,4 @@ Module Program ' End Sub End Module -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEmitCodeInPartialTrust/vb/source.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEmitCodeInPartialTrust/vb/source.vb index 5a12b4fbe57c5..69ba7682b3a69 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEmitCodeInPartialTrust/vb/source.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEmitCodeInPartialTrust/vb/source.vb @@ -12,9 +12,9 @@ Imports System.Diagnostics ' Delegates used to execute the dynamic methods. ' -Public Delegate Sub Test(ByVal w As Worker) -Public Delegate Sub Test1() -Public Delegate Function Test2(ByVal instance As String) As Char +Public Delegate Sub Test(ByVal w As Worker) +Public Delegate Sub Test1() +Public Delegate Function Test2(ByVal instance As String) As Char ' The Worker class must inherit MarshalByRefObject so that its public ' methods can be invoked across application domain boundaries. @@ -22,15 +22,15 @@ Public Delegate Function Test2(ByVal instance As String) As Char ' Public Class Worker Inherits MarshalByRefObject -' - - Private Sub PrivateMethod() + ' + + Private Sub PrivateMethod() Console.WriteLine("Worker.PrivateMethod()") - End Sub + End Sub ' Public Sub SimpleEmitDemo() - + ' Dim meth As DynamicMethod = new DynamicMethod("", Nothing, Nothing) Dim il As ILGenerator = meth.GetILGenerator() @@ -42,36 +42,36 @@ Public Class Worker t1() End Sub ' - + ' This overload of AccessPrivateMethod emits a dynamic method and ' specifies whether to skip JIT visiblity checks. It creates a ' delegate for the method and invokes the delegate. The dynamic ' method calls a private method of the Worker class. Overloads Public Sub AccessPrivateMethod( _ - ByVal restrictedSkipVisibility As Boolean) + ByVal restrictedSkipVisibility As Boolean) ' Create an unnamed dynamic method that has no return type, ' takes one parameter of type Worker, and optionally skips JIT ' visiblity checks. Dim meth As New DynamicMethod("", _ Nothing, _ - New Type() { GetType(Worker) }, _ + New Type() {GetType(Worker)}, _ restrictedSkipVisibility) - + ' Get a MethodInfo for the private method. Dim pvtMeth As MethodInfo = GetType(Worker).GetMethod( _ "PrivateMethod", _ BindingFlags.NonPublic Or BindingFlags.Instance) - + ' Get an ILGenerator and emit a body for the dynamic method. Dim il As ILGenerator = meth.GetILGenerator() - + ' Load the first argument, which is the target instance, onto the ' execution stack, call the private method, and return. il.Emit(OpCodes.Ldarg_0) il.EmitCall(OpCodes.Call, pvtMeth, Nothing) il.Emit(OpCodes.Ret) - + ' Create a delegate that represents the dynamic method, and ' invoke it. Try @@ -86,14 +86,14 @@ Public Class Worker Console.WriteLine("{0} was thrown when the delegate was compiled.", _ ex.GetType().Name) End Try - - End Sub - - + + End Sub + + ' This overload of AccessPrivateMethod emits a dynamic method that takes ' a string and returns the first character, using a private field of the ' String class. The dynamic method skips JIT visiblity checks. - Overloads Public Sub AccessPrivateMethod() + Overloads Public Sub AccessPrivateMethod() ' Dim meth As New DynamicMethod("", _ @@ -101,23 +101,23 @@ Public Class Worker New Type() {GetType(String)}, _ True) ' - + ' Get a MethodInfo for the 'get' accessor of the private property. Dim pi As PropertyInfo = GetType(String).GetProperty( _ "FirstChar", _ - BindingFlags.NonPublic Or BindingFlags.Instance) + BindingFlags.NonPublic Or BindingFlags.Instance) Dim pvtMeth As MethodInfo = pi.GetGetMethod(True) - + ' Get an ILGenerator and emit a body for the dynamic method. Dim il As ILGenerator = meth.GetILGenerator() - + ' Load the first argument, which is the target string, onto the ' execution stack, call the 'get' accessor to put the result onto ' the execution stack, and return. il.Emit(OpCodes.Ldarg_0) il.EmitCall(OpCodes.Call, pvtMeth, Nothing) il.Emit(OpCodes.Ret) - + ' Create a delegate that represents the dynamic method, and ' invoke it. Try @@ -128,21 +128,21 @@ Public Class Worker Console.WriteLine("{0} was thrown when the delegate was compiled.", _ ex.GetType().Name) End Try - - End Sub + + End Sub End Class Friend Class Example ' The entry point for the code example. - Shared Sub Main() + Shared Sub Main() ' Get the display name of the executing assembly, to use when ' creating objects to run code in application domains. ' Dim asmName As String = GetType(Worker).Assembly.FullName ' - + ' Create the permission set to grant to other assemblies. In this ' case they are the permissions found in the Internet zone. ' @@ -165,7 +165,7 @@ Friend Class Example ' Dim ad As AppDomain = AppDomain.CreateDomain("Sandbox", ev, adSetup, pset, Nothing) ' - + ' Create an instance of the Worker class in the partially trusted ' domain. Note: If you build this code example in Visual Studio, ' you must change the name of the class to include the default @@ -180,18 +180,18 @@ Friend Class Example ' w.SimpleEmitDemo() ' - + ' Emit and invoke a dynamic method that calls a private method ' of Worker, with JIT visibility checks enforced. The call fails ' when the delegate is invoked. w.AccessPrivateMethod(False) - + ' Emit and invoke a dynamic method that calls a private method ' of Worker, skipping JIT visibility checks. The call fails when ' the method is compiled. w.AccessPrivateMethod(True) - - + + ' Unload the application domain. Add RestrictedMemberAccess to the ' grant set, and use it to create an application domain in which ' partially trusted code can call private members, as long as the @@ -206,24 +206,24 @@ Friend Class Example ' ad = AppDomain.CreateDomain("Sandbox2", ev, adSetup, pset, Nothing) ' - + ' Create an instance of the Worker class in the partially trusted ' domain. w = CType(ad.CreateInstanceAndUnwrap(asmName, "Worker"), Worker) - + ' Again, emit and invoke a dynamic method that calls a private method ' of Worker, skipping JIT visibility checks. This time compilation ' succeeds because of the grant for RestrictedMemberAccess. w.AccessPrivateMethod(True) - + ' Finally, emit and invoke a dynamic method that calls an internal ' method of the String class. The call fails, because the trust level ' of the assembly that contains String is higher than the trust level ' of the assembly that emits the dynamic method. w.AccessPrivateMethod() - - End Sub -End Class + + End Sub +End Class ' This code example produces the following output: ' @@ -233,4 +233,4 @@ End Class 'Worker.PrivateMethod() 'MethodAccessException was thrown when the delegate was compiled. ' -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEncryptXMLElementAsymmetric/vb/sample.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEncryptXMLElementAsymmetric/vb/sample.vb index d3b81852c3bf3..a6511754dc7c1 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEncryptXMLElementAsymmetric/vb/sample.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEncryptXMLElementAsymmetric/vb/sample.vb @@ -220,4 +220,4 @@ Class Program End Class -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEncryptXMLElementSymmetric/vb/sample.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEncryptXMLElementSymmetric/vb/sample.vb index 48bddbd31864e..e29e498ab5ff4 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEncryptXMLElementSymmetric/vb/sample.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEncryptXMLElementSymmetric/vb/sample.vb @@ -129,10 +129,10 @@ Module Program '''''''''''''''''''''''''''''''''''''''''''''''''' ' EncryptedXml.ReplaceElement(elementToEncrypt, edElement, False) - ' + ' End Sub - + Sub Decrypt(ByVal Doc As XmlDocument, ByVal Alg As SymmetricAlgorithm) ' Check the arguments. @@ -173,4 +173,4 @@ Module Program End Sub End Module -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEncryptXMLElementX509/vb/sample.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEncryptXMLElementX509/vb/sample.vb index bc9f2ac812c04..a558331fcdbed 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEncryptXMLElementX509/vb/sample.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToEncryptXMLElementX509/vb/sample.vb @@ -114,4 +114,4 @@ Module Program ' End Sub End Module -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/source2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/source2.vb index b83f2842111b4..a49b6ac9aab85 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/source2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/source2.vb @@ -4,7 +4,7 @@ Imports System.Collections.Generic Class AdvantageGenerics Public Shared Sub Main() Dim myArray() As String = _ - {"First String", "test string", "Last String"} + {"First String", "test string", "Last String"} ' Dim llist As New LinkedList(Of String)() diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb index 1036a29511487..a3647e01f2df1 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb @@ -34,9 +34,9 @@ Public Class Example Private Shared Sub DisplayGenericType(ByVal t As Type) Console.WriteLine(vbCrLf & t.ToString()) ' - Console.WriteLine(" Is this a generic type? " _ + Console.WriteLine(" Is this a generic type? " _ & t.IsGenericType) - Console.WriteLine(" Is this a generic type definition? " _ + Console.WriteLine(" Is this a generic type definition? " _ & t.IsGenericTypeDefinition) ' @@ -150,7 +150,7 @@ Public Class Example ' dictionary is Example. ' Dim typeArgs() As Type = _ - { GetType(String), GetType(Example) } + {GetType(String), GetType(Example)} ' ' Construct the type Dictionary(Of String, Example). @@ -169,7 +169,7 @@ Public Class Example "Compare types obtained by different methods:") Console.WriteLine(" Are the constructed types equal? " _ & (d2.GetType() Is constructed)) - Console.WriteLine(" Are the generic definitions equal? " _ + Console.WriteLine(" Are the generic definitions equal? " _ & (d1 Is constructed.GetGenericTypeDefinition())) ' Demonstrate the DisplayGenericType and @@ -179,4 +179,4 @@ Public Class Example DisplayGenericType(GetType(Test(Of ))) End Sub End Class -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToVerifyXMLDocumentRSA/vb/sample.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToVerifyXMLDocumentRSA/vb/sample.vb index d205b80f8e8c3..78fb9a1b15612 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/HowToVerifyXMLDocumentRSA/vb/sample.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/HowToVerifyXMLDocumentRSA/vb/sample.vb @@ -83,4 +83,4 @@ Module VerifyXML ' End Function End Module -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/IO.File.GetAccessControl-SetAccessControl/VB/sample.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/IO.File.GetAccessControl-SetAccessControl/VB/sample.vb index 81ec0875f470f..eeda6a40365bc 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/IO.File.GetAccessControl-SetAccessControl/VB/sample.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/IO.File.GetAccessControl-SetAccessControl/VB/sample.vb @@ -33,7 +33,7 @@ Module FileExample ' Adds an ACL entry on the specified file for the specified account. Sub AddFileSecurity(ByVal fileName As String, ByVal account As String, _ ByVal rights As FileSystemRights, ByVal controlType As AccessControlType) - + ' Get a FileSecurity object that represents the ' current security settings. Dim fSecurity As FileSecurity = File.GetAccessControl(fileName) @@ -67,4 +67,4 @@ Module FileExample End Sub End Module -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Classes/vb/Example.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Classes/vb/Example.vb index 315699566d2bc..2066aba6912be 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Classes/vb/Example.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Classes/vb/Example.vb @@ -5,204 +5,204 @@ Imports System.Collections.Generic Imports System.Text.RegularExpressions Module Example - Public Sub Main() - InstantiateRegex() - UseMatch() - Console.WriteLine() - UseMatchCollection() - Console.WriteLine() - UseGroupCollection() - Console.WriteLine() - UseCaptureCollection() - Console.WriteLine() - UseGroup() - Console.WriteLine() - UseCapture() - Console.WriteLine() - UseNamedGroups() - End Sub - - Private Sub InstantiateRegex - ' - ' Declare object variable of type Regex. - Dim r As Regex - ' Create a Regex object and define its regular expression. - r = New Regex("\s2000") - ' - End Sub - - Private Sub UseMatch() - ' - ' Create a new Regex object. - Dim r As New Regex("abc") - ' Find a single match in the input string. - Dim m As Match = r.Match("123abc456") - If m.Success Then - ' Print out the character position where a match was found. - Console.WriteLine("Found match at position " & m.Index.ToString()) - End If - ' The example displays the following output: - ' Found match at position 3 - ' - End Sub - - Private Sub UseMatchCollection() - ' - Dim mc As MatchCollection - Dim results As New List(Of String) - Dim matchposition As New List(Of Integer) - - ' Create a new Regex object and define the regular expression. - Dim r As New Regex("abc") - ' Use the Matches method to find all matches in the input string. - mc = r.Matches("123abc4abcd") - ' Loop through the match collection to retrieve all - ' matches and positions. - For i As Integer = 0 To mc.Count - 1 - ' Add the match string to the string array. - results.Add(mc(i).Value) - ' Record the character position where the match was found. - matchposition.Add(mc(i).Index) - Next i - ' List the results. - For ctr As Integer = 0 To Results.Count - 1 - Console.WriteLine("'{0}' found at position {1}.", _ - results(ctr), matchposition(ctr)) - Next - ' The example displays the following output: - ' 'abc' found at position 3. - ' 'abc' found at position 7. - ' - End Sub - - Public Sub UseGroupCollection - ' - ' Define groups "abc", "ab", and "b". - Dim r As New Regex("(a(b))c") - Dim m As Match = r.Match("abdabc") - Console.WriteLine("Number of groups found = " _ - & m.Groups.Count) - ' The example displays the following output: - ' Number of groups found = 3 - ' - End Sub - - Private Sub UseCaptureCollection() - ' - Dim counter As Integer - Dim m As Match - Dim cc As CaptureCollection - Dim gc As GroupCollection - - ' Look for groupings of "Abc". - Dim r As New Regex("(Abc)+") - ' Define the string to search. - m = r.Match("XYZAbcAbcAbcXYZAbcAb") - gc = m.Groups - - ' Display the number of groups. - Console.WriteLine("Captured groups = " & gc.Count.ToString()) - - ' Loop through each group. - Dim i, ii As Integer - For i = 0 To gc.Count - 1 - cc = gc(i).Captures - counter = cc.Count - - ' Display the number of captures in this group. - Console.WriteLine("Captures count = " & counter.ToString()) - - ' Loop through each capture in the group. - For ii = 0 To counter - 1 - ' Display the capture and its position. - Console.WriteLine(cc(ii).ToString() _ - & " Starts at character " & cc(ii).Index.ToString()) - Next ii - Next i - ' The example displays the following output: - ' Captured groups = 2 - ' Captures count = 1 - ' AbcAbcAbc Starts at character 3 - ' Captures count = 3 - ' Abc Starts at character 3 - ' Abc Starts at character 6 - ' Abc Starts at character 9 - ' - End Sub - - Private Sub UseGroup() - ' - Dim matchposition As New List(Of Integer) - Dim results As New List(Of String) - ' Define substrings abc, ab, b. - Dim r As New Regex("(a(b))c") - Dim m As Match = r.Match("abdabc") - Dim i As Integer = 0 - While Not (m.Groups(i).Value = "") - ' Add groups to string array. - results.Add(m.Groups(i).Value) - ' Record character position. - matchposition.Add(m.Groups(i).Index) - i += 1 - End While - - ' Display the capture groups. - For ctr As Integer = 0 to results.Count - 1 - Console.WriteLine("{0} at position {1}", _ - results(ctr), matchposition(ctr)) - Next - ' The example displays the following output: - ' abc at position 3 - ' ab at position 3 - ' b at position 4 - ' - End Sub - - Private Sub UseCapture() - ' - Dim r As Regex - Dim m As Match - Dim cc As CaptureCollection - Dim posn, length As Integer - - r = New Regex("(abc)+") - m = r.Match("bcabcabc") - Dim i, j As Integer - i = 0 - Do While m.Groups(i).Value <> "" - Console.WriteLine(m.Groups(i).Value) - ' Grab the Collection for Group(i). - cc = m.Groups(i).Captures - For j = 0 To cc.Count - 1 - - Console.WriteLine(" Capture at position {0} for {1} characters.", _ - cc(j).Index, cc(j).Length) - ' Position of Capture object. - posn = cc(j).Index - ' Length of Capture object. - length = cc(j).Length - Next j - i += 1 - Loop - ' The example displays the following output: - ' abcabc - ' Capture at position 2 for 6 characters. - ' abc - ' Capture at position 2 for 3 characters. - ' Capture at position 5 for 3 characters. - ' - End Sub - - Private Sub UseNamedGroups() - ' - Dim r As New Regex("^(?\w+):(?\w+)") - Dim m As Match = r.Match("Section1:119900") - Console.WriteLine(m.Groups("name").Value) - Console.WriteLine(m.Groups("value").Value) - ' The example displays the following output: - ' Section1 - ' 119900 - ' - End Sub + Public Sub Main() + InstantiateRegex() + UseMatch() + Console.WriteLine() + UseMatchCollection() + Console.WriteLine() + UseGroupCollection() + Console.WriteLine() + UseCaptureCollection() + Console.WriteLine() + UseGroup() + Console.WriteLine() + UseCapture() + Console.WriteLine() + UseNamedGroups() + End Sub + + Private Sub InstantiateRegex + ' + ' Declare object variable of type Regex. + Dim r As Regex + ' Create a Regex object and define its regular expression. + r = New Regex("\s2000") + ' + End Sub + + Private Sub UseMatch() + ' + ' Create a new Regex object. + Dim r As New Regex("abc") + ' Find a single match in the input string. + Dim m As Match = r.Match("123abc456") + If m.Success Then + ' Print out the character position where a match was found. + Console.WriteLine("Found match at position " & m.Index.ToString()) + End If + ' The example displays the following output: + ' Found match at position 3 + ' + End Sub + + Private Sub UseMatchCollection() + ' + Dim mc As MatchCollection + Dim results As New List(Of String) + Dim matchposition As New List(Of Integer) + + ' Create a new Regex object and define the regular expression. + Dim r As New Regex("abc") + ' Use the Matches method to find all matches in the input string. + mc = r.Matches("123abc4abcd") + ' Loop through the match collection to retrieve all + ' matches and positions. + For i As Integer = 0 To mc.Count - 1 + ' Add the match string to the string array. + results.Add(mc(i).Value) + ' Record the character position where the match was found. + matchposition.Add(mc(i).Index) + Next i + ' List the results. + For ctr As Integer = 0 To Results.Count - 1 + Console.WriteLine("'{0}' found at position {1}.", _ + results(ctr), matchposition(ctr)) + Next + ' The example displays the following output: + ' 'abc' found at position 3. + ' 'abc' found at position 7. + ' + End Sub + + Public Sub UseGroupCollection + ' + ' Define groups "abc", "ab", and "b". + Dim r As New Regex("(a(b))c") + Dim m As Match = r.Match("abdabc") + Console.WriteLine("Number of groups found = " _ + & m.Groups.Count) + ' The example displays the following output: + ' Number of groups found = 3 + ' + End Sub + + Private Sub UseCaptureCollection() + ' + Dim counter As Integer + Dim m As Match + Dim cc As CaptureCollection + Dim gc As GroupCollection + + ' Look for groupings of "Abc". + Dim r As New Regex("(Abc)+") + ' Define the string to search. + m = r.Match("XYZAbcAbcAbcXYZAbcAb") + gc = m.Groups + + ' Display the number of groups. + Console.WriteLine("Captured groups = " & gc.Count.ToString()) + + ' Loop through each group. + Dim i, ii As Integer + For i = 0 To gc.Count - 1 + cc = gc(i).Captures + counter = cc.Count + + ' Display the number of captures in this group. + Console.WriteLine("Captures count = " & counter.ToString()) + + ' Loop through each capture in the group. + For ii = 0 To counter - 1 + ' Display the capture and its position. + Console.WriteLine(cc(ii).ToString() _ + & " Starts at character " & cc(ii).Index.ToString()) + Next ii + Next i + ' The example displays the following output: + ' Captured groups = 2 + ' Captures count = 1 + ' AbcAbcAbc Starts at character 3 + ' Captures count = 3 + ' Abc Starts at character 3 + ' Abc Starts at character 6 + ' Abc Starts at character 9 + ' + End Sub + + Private Sub UseGroup() + ' + Dim matchposition As New List(Of Integer) + Dim results As New List(Of String) + ' Define substrings abc, ab, b. + Dim r As New Regex("(a(b))c") + Dim m As Match = r.Match("abdabc") + Dim i As Integer = 0 + While Not (m.Groups(i).Value = "") + ' Add groups to string array. + results.Add(m.Groups(i).Value) + ' Record character position. + matchposition.Add(m.Groups(i).Index) + i += 1 + End While + + ' Display the capture groups. + For ctr As Integer = 0 to results.Count - 1 + Console.WriteLine("{0} at position {1}", _ + results(ctr), matchposition(ctr)) + Next + ' The example displays the following output: + ' abc at position 3 + ' ab at position 3 + ' b at position 4 + ' + End Sub + + Private Sub UseCapture() + ' + Dim r As Regex + Dim m As Match + Dim cc As CaptureCollection + Dim posn, length As Integer + + r = New Regex("(abc)+") + m = r.Match("bcabcabc") + Dim i, j As Integer + i = 0 + Do While m.Groups(i).Value <> "" + Console.WriteLine(m.Groups(i).Value) + ' Grab the Collection for Group(i). + cc = m.Groups(i).Captures + For j = 0 To cc.Count - 1 + + Console.WriteLine(" Capture at position {0} for {1} characters.", _ + cc(j).Index, cc(j).Length) + ' Position of Capture object. + posn = cc(j).Index + ' Length of Capture object. + length = cc(j).Length + Next j + i += 1 + Loop + ' The example displays the following output: + ' abcabc + ' Capture at position 2 for 6 characters. + ' abc + ' Capture at position 2 for 3 characters. + ' Capture at position 5 for 3 characters. + ' + End Sub + + Private Sub UseNamedGroups() + ' + Dim r As New Regex("^(?\w+):(?\w+)") + Dim m As Match = r.Match("Section1:119900") + Console.WriteLine(m.Groups("name").Value) + Console.WriteLine(m.Groups("value").Value) + ' The example displays the following output: + ' Section1 + ' 119900 + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.ChangeDateFormats/vb/Example_ChangeDateFormats1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.ChangeDateFormats/vb/Example_ChangeDateFormats1.vb index 6aeec61a23a92..cb15ac7701c53 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.ChangeDateFormats/vb/Example_ChangeDateFormats1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.ChangeDateFormats/vb/Example_ChangeDateFormats1.vb @@ -6,23 +6,23 @@ Imports System.Globalization Imports System.Text.RegularExpressions Module DateFormatReplacement - Public Sub Main() - Dim dateString As String = Date.Today.ToString("d", _ - DateTimeFormatInfo.InvariantInfo) - Dim resultString As String = MDYToDMY(dateString) - Console.WriteLine("Converted {0} to {1}.", dateString, resultString) - End Sub + Public Sub Main() + Dim dateString As String = Date.Today.ToString("d", _ + DateTimeFormatInfo.InvariantInfo) + Dim resultString As String = MDYToDMY(dateString) + Console.WriteLine("Converted {0} to {1}.", dateString, resultString) + End Sub - ' + ' Function MDYToDMY(input As String) As String - Try - Return Regex.Replace(input, _ - "\b(?\d{1,2})/(?\d{1,2})/(?\d{2,4})\b", _ - "${day}-${month}-${year}", RegexOptions.None, - TimeSpan.FromMilliseconds(150)) + Try + Return Regex.Replace(input, _ + "\b(?\d{1,2})/(?\d{1,2})/(?\d{2,4})\b", _ + "${day}-${month}-${year}", RegexOptions.None, + TimeSpan.FromMilliseconds(150)) Catch e As RegexMatchTimeoutException - Return input - End Try + Return input + End Try End Function ' End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/Example.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/Example.vb index 98625981041e5..7861b3b5640f4 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/Example.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/Example.vb @@ -5,28 +5,28 @@ Option Strict On Imports System.Text.RegularExpressions Module RegexUtilities - Function IsValidEmail(strIn As String) As Boolean - ' Return true if strIn is in valid email format. - Return Regex.IsMatch(strIn, _ - "^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$") - End Function + Function IsValidEmail(strIn As String) As Boolean + ' Return true if strIn is in valid email format. + Return Regex.IsMatch(strIn, _ + "^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$") + End Function End Module ' ' Public Class Application - Public Shared Sub Main() - Dim emailAddresses() As String = { "david.jones@proseware.com", "d.j@server1.proseware.com", _ - "jones@ms1.proseware.com", "j.@server1.proseware.com", _ - "j@proseware.com9" } - For Each emailAddress As String In emailAddresses - If RegexUtilities.IsValidEmail(emailAddress) Then - Console.WriteLine("Valid: {0}", emailAddress) - Else - Console.WriteLine("Invalid: {0}", emailAddress) - End If - Next - End Sub + Public Shared Sub Main() + Dim emailAddresses() As String = {"david.jones@proseware.com", "d.j@server1.proseware.com", _ + "jones@ms1.proseware.com", "j.@server1.proseware.com", _ + "j@proseware.com9"} + For Each emailAddress As String In emailAddresses + If RegexUtilities.IsValidEmail(emailAddress) Then + Console.WriteLine("Valid: {0}", emailAddress) + Else + Console.WriteLine("Invalid: {0}", emailAddress) + End If + Next + End Sub End Class ' The example displays the following output: ' Valid: david.jones@proseware.com diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/example2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/example2.vb index da7f53bc03115..ef44564b3b150 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/example2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/example2.vb @@ -5,33 +5,33 @@ Option Strict On Imports System.Text.RegularExpressions Module RegexUtilities - Function IsValidEmail(strIn As String) As Boolean - ' Return true if strIn is in valid email format. - Return Regex.IsMatch(strIn, _ - "^(?("")(""[^""]+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" + _ - "(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$") - End Function + Function IsValidEmail(strIn As String) As Boolean + ' Return true if strIn is in valid email format. + Return Regex.IsMatch(strIn, _ + "^(?("")(""[^""]+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" + _ + "(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$") + End Function End Module ' ' Public Class Application - Public Shared Sub Main() - Dim emailAddresses() As String = { "david.jones@proseware.com", "d.j@server1.proseware.com", _ - "jones@ms1.proseware.com", "j.@server1.proseware.com", _ - "j@proseware.com9", "js#internal@proseware.com", _ - "j_9@[129.126.118.1]", "j..s@proseware.com", _ - "js*@proseware.com", "js@proseware..com", _ - "js@proseware.com9", "j.s@server1.proseware.com" } + Public Shared Sub Main() + Dim emailAddresses() As String = {"david.jones@proseware.com", "d.j@server1.proseware.com", _ + "jones@ms1.proseware.com", "j.@server1.proseware.com", _ + "j@proseware.com9", "js#internal@proseware.com", _ + "j_9@[129.126.118.1]", "j..s@proseware.com", _ + "js*@proseware.com", "js@proseware..com", _ + "js@proseware.com9", "j.s@server1.proseware.com"} - For Each emailAddress As String In emailAddresses - If RegexUtilities.IsValidEmail(emailAddress) Then - Console.WriteLine("Valid: {0}", emailAddress) - Else - Console.WriteLine("Invalid: {0}", emailAddress) - End If - Next - End Sub + For Each emailAddress As String In emailAddresses + If RegexUtilities.IsValidEmail(emailAddress) Then + Console.WriteLine("Valid: {0}", emailAddress) + Else + Console.WriteLine("Invalid: {0}", emailAddress) + End If + Next + End Sub End Class ' The example displays the following output: ' Valid: david.jones@proseware.com diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/example3.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/example3.vb index b50f8c3240980..d4f1778f48e13 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/example3.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/example3.vb @@ -6,67 +6,67 @@ Imports System.Globalization Imports System.Text.RegularExpressions Public Class RegexUtilities - Dim invalid As Boolean = False - - public Function IsValidEmail(strIn As String) As Boolean - invalid = False - If String.IsNullOrEmpty(strIn) Then Return False - - ' Use IdnMapping class to convert Unicode domain names. - Try - strIn = Regex.Replace(strIn, "(@)(.+)$", AddressOf Me.DomainMapper, - RegexOptions.None, TimeSpan.FromMilliseconds(200)) - Catch e As RegexMatchTimeoutException - Return False - End Try - - If invalid Then Return False - - ' Return true if strIn is in valid email format. - Try - Return Regex.IsMatch(strIn, _ - "^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + _ - "(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,24}))$", - RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)) - Catch e As RegexMatchTimeoutException - Return False - End Try - End Function - - Private Function DomainMapper(match As Match) As String - ' IdnMapping class with default property values. - Dim idn As New IdnMapping() + Dim invalid As Boolean = False - Dim domainName As String = match.Groups(2).Value - Try - domainName = idn.GetAscii(domainName) - Catch e As ArgumentException - invalid = True - End Try - Return match.Groups(1).Value + domainName - End Function + public Function IsValidEmail(strIn As String) As Boolean + invalid = False + If String.IsNullOrEmpty(strIn) Then Return False + + ' Use IdnMapping class to convert Unicode domain names. + Try + strIn = Regex.Replace(strIn, "(@)(.+)$", AddressOf Me.DomainMapper, + RegexOptions.None, TimeSpan.FromMilliseconds(200)) + Catch e As RegexMatchTimeoutException + Return False + End Try + + If invalid Then Return False + + ' Return true if strIn is in valid email format. + Try + Return Regex.IsMatch(strIn, _ + "^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + _ + "(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,24}))$", + RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)) + Catch e As RegexMatchTimeoutException + Return False + End Try + End Function + + Private Function DomainMapper(match As Match) As String + ' IdnMapping class with default property values. + Dim idn As New IdnMapping() + + Dim domainName As String = match.Groups(2).Value + Try + domainName = idn.GetAscii(domainName) + Catch e As ArgumentException + invalid = True + End Try + Return match.Groups(1).Value + domainName + End Function End Class ' ' Public Class Application - Public Shared Sub Main() - Dim util As New RegexUtilities() - Dim emailAddresses() As String = { "david.jones@proseware.com", "d.j@server1.proseware.com", _ - "jones@ms1.proseware.com", "j.@server1.proseware.com", _ - "j@proseware.com9", "js#internal@proseware.com", _ - "j_9@[129.126.118.1]", "j..s@proseware.com", _ - "js*@proseware.com", "js@proseware..com", _ - "js@proseware.com9", "j.s@server1.proseware.com" } + Public Shared Sub Main() + Dim util As New RegexUtilities() + Dim emailAddresses() As String = {"david.jones@proseware.com", "d.j@server1.proseware.com", _ + "jones@ms1.proseware.com", "j.@server1.proseware.com", _ + "j@proseware.com9", "js#internal@proseware.com", _ + "j_9@[129.126.118.1]", "j..s@proseware.com", _ + "js*@proseware.com", "js@proseware..com", _ + "js@proseware.com9", "j.s@server1.proseware.com"} - For Each emailAddress As String In emailAddresses - If util.IsValidEmail(emailAddress) Then - Console.WriteLine("Valid: {0}", emailAddress) - Else - Console.WriteLine("Invalid: {0}", emailAddress) - End If - Next - End Sub + For Each emailAddress As String In emailAddresses + If util.IsValidEmail(emailAddress) Then + Console.WriteLine("Valid: {0}", emailAddress) + Else + Console.WriteLine("Invalid: {0}", emailAddress) + End If + Next + End Sub End Class ' The example displays the following output: ' Valid: david.jones@proseware.com diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/example4.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/example4.vb index b05ec0a3fed19..d7eba482ff9b7 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/example4.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Email/vb/example4.vb @@ -24,7 +24,7 @@ Public Class RegexUtilities Dim domainName As String = idn.GetAscii(match.Groups(2).Value) Return match.Groups(1).Value & domainName - + End Function 'Normalize the domain @@ -57,23 +57,23 @@ End Class ' Public Class Application - Public Shared Sub Main() - Dim emailAddresses() As String = {"david.jones@proseware.com", "d.j@server1.proseware.com", - "jones@ms1.proseware.com", "j.@server1.proseware.com", - "j@proseware.com9", "js#internal@proseware.com", - "j_9@[129.126.118.1]", "j..s@proseware.com", - "js*@proseware.com", "js@proseware..com", - "js@proseware.com9", "j.s@server1.proseware.com", - """j\""s\""""@proseware.com", "js@contoso.中国"} - - For Each emailAddress As String In emailAddresses - If RegexUtilities.IsValidEmail(emailAddress) Then - Console.WriteLine($"Valid: {emailAddress}") - Else - Console.WriteLine($"Invalid: {emailAddress}") - End If - Next - End Sub + Public Shared Sub Main() + Dim emailAddresses() As String = {"david.jones@proseware.com", "d.j@server1.proseware.com", + "jones@ms1.proseware.com", "j.@server1.proseware.com", + "j@proseware.com9", "js#internal@proseware.com", + "j_9@[129.126.118.1]", "j..s@proseware.com", + "js*@proseware.com", "js@proseware..com", + "js@proseware.com9", "j.s@server1.proseware.com", + """j\""s\""""@proseware.com", "js@contoso.中国"} + + For Each emailAddress As String In emailAddresses + If RegexUtilities.IsValidEmail(emailAddress) Then + Console.WriteLine($"Valid: {emailAddress}") + Else + Console.WriteLine($"Invalid: {emailAddress}") + End If + Next + End Sub End Class ' The example displays the following output: ' Valid: david.jones@proseware.com @@ -90,4 +90,4 @@ End Class ' Valid: j.s@server1.proseware.com ' Valid: "j\"s\""@proseware.com ' Valid: js@contoso.中国 -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.HREF/vb/example.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.HREF/vb/example.vb index ebd2504e3a27b..f22b2e4a17133 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.HREF/vb/example.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.HREF/vb/example.vb @@ -5,40 +5,40 @@ Imports System.Text.RegularExpressions Public Module Example - ' - Public Sub Main() - Dim inputString As String = "My favorite web sites include:

" & _ - "" & _ - "MSDN Home Page

" & _ - "" & _ - "Microsoft Corporation Home Page

" & _ - "" & _ - ".NET Base Class Library blog

" - DumpHRefs(inputString) - End Sub - ' The example displays the following output: - ' Found href http://msdn2.microsoft.com at 43 - ' Found href http://www.microsoft.com at 102 - ' Found href http://blogs.msdn.com/bclteam/) at 176 - '
- - ' - Private Sub DumpHRefs(inputString As String) - Dim m As Match - Dim HRefPattern As String = "href\s*=\s*(?:[""'](?<1>[^""']*)[""']|(?<1>\S+))" - - Try - m = Regex.Match(inputString, HRefPattern, _ - RegexOptions.IgnoreCase Or RegexOptions.Compiled, - TimeSpan.FromSeconds(1)) - Do While m.Success - Console.WriteLine("Found href {0} at {1}.", _ - m.Groups(1), m.Groups(1).Index) - m = m.NextMatch() - Loop - Catch e As RegexMatchTimeoutException - Console.WriteLine("The matching operation timed out.") - End Try - End Sub - ' + ' + Public Sub Main() + Dim inputString As String = "My favorite web sites include:

" & _ + "" & _ + "MSDN Home Page

" & _ + "" & _ + "Microsoft Corporation Home Page

" & _ + "" & _ + ".NET Base Class Library blog

" + DumpHRefs(inputString) + End Sub + ' The example displays the following output: + ' Found href http://msdn2.microsoft.com at 43 + ' Found href http://www.microsoft.com at 102 + ' Found href http://blogs.msdn.com/bclteam/) at 176 + '
+ + ' + Private Sub DumpHRefs(inputString As String) + Dim m As Match + Dim HRefPattern As String = "href\s*=\s*(?:[""'](?<1>[^""']*)[""']|(?<1>\S+))" + + Try + m = Regex.Match(inputString, HRefPattern, _ + RegexOptions.IgnoreCase Or RegexOptions.Compiled, + TimeSpan.FromSeconds(1)) + Do While m.Success + Console.WriteLine("Found href {0} at {1}.", _ + m.Groups(1), m.Groups(1).Index) + m = m.NextMatch() + Loop + Catch e As RegexMatchTimeoutException + Console.WriteLine("The matching operation timed out.") + End Try + End Sub + ' End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Protocol/vb/Example.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Protocol/vb/Example.vb index 7066a4c33bbe7..fe4f45a8987f9 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Protocol/vb/Example.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Protocol/vb/Example.vb @@ -5,16 +5,16 @@ Option Strict On Imports System.Text.RegularExpressions Module Example - Public Sub Main() - Dim url As String = "http://www.contoso.com:8080/letters/readme.html" - Dim r As New Regex("^(?\w+)://[^/]+?(?:\d+)?/", - RegexOptions.None, TimeSpan.FromMilliseconds(150)) + Public Sub Main() + Dim url As String = "http://www.contoso.com:8080/letters/readme.html" + Dim r As New Regex("^(?\w+)://[^/]+?(?:\d+)?/", + RegexOptions.None, TimeSpan.FromMilliseconds(150)) - Dim m As Match = r.Match(url) - If m.Success Then - Console.WriteLine(m.Result("${proto}${port}")) - End If - End Sub + Dim m As Match = r.Match(url) + If m.Success Then + Console.WriteLine(m.Result("${proto}${port}")) + End If + End Sub End Module ' The example displays the following output: ' http:8080 diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Protocol/vb/example2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Protocol/vb/example2.vb index 491eae76dcbcf..685ef467e5979 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Protocol/vb/example2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.Protocol/vb/example2.vb @@ -4,17 +4,17 @@ Option Strict On Imports System.Text.RegularExpressions Module Example - Public Sub Main() - Dim url As String = "http://www.contoso.com:8080/letters/readme.html" - Dim r As New Regex("^(?\w+)://[^/]+?(?:\d+)?/", - RegexOptions.None, TimeSpan.FromMilliseconds(150)) - Dim m As Match = r.Match(url) - If m.Success Then -' - Console.WriteLine(m.Groups("proto").Value + m.Groups("port").Value) -' - End If - End Sub + Public Sub Main() + Dim url As String = "http://www.contoso.com:8080/letters/readme.html" + Dim r As New Regex("^(?\w+)://[^/]+?(?:\d+)?/", + RegexOptions.None, TimeSpan.FromMilliseconds(150)) + Dim m As Match = r.Match(url) + If m.Success Then + ' + Console.WriteLine(m.Groups("proto").Value + m.Groups("port").Value) + ' + End If + End Sub End Module ' The example displays the following output: ' http:8080 diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.StripChars/vb/Example.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.StripChars/vb/Example.vb index fc09f6e8a72d9..3e11697ac0ac4 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.StripChars/vb/Example.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Examples.StripChars/vb/Example.vb @@ -8,11 +8,11 @@ Module Example Function CleanInput(strIn As String) As String ' Replace invalid characters with empty strings. Try - Return Regex.Replace(strIn, "[^\w\.@-]", "") - ' If we timeout when replacing invalid characters, - ' we should return String.Empty. + Return Regex.Replace(strIn, "[^\w\.@-]", "") + ' If we timeout when replacing invalid characters, + ' we should return String.Empty. Catch e As RegexMatchTimeoutException - Return String.Empty + Return String.Empty End Try End Function End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Quantifiers.Greedy/vb/Greedy.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Quantifiers.Greedy/vb/Greedy.vb index 5f579fe58d32d..a9e94de05c6e9 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Quantifiers.Greedy/vb/Greedy.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Quantifiers.Greedy/vb/Greedy.vb @@ -5,27 +5,27 @@ Imports System.Text.RegularExpressions Module modMain - Public Sub Main() - ' - Dim greedyPattern As String = "\b.*([0-9]{4})\b" - Dim input1 As String = "1112223333 3992991999" - For Each match As Match In Regex.Matches(input1, greedypattern) - Console.WriteLine("Account ending in ******{0}.", match.Groups(1).Value) - Next - ' The example displays the following output: - ' Account ending in ******1999. - ' - Console.WriteLine() - ' - Dim lazyPattern As String = "\b.*?([0-9]{4})\b" - Dim input2 As String = "1112223333 3992991999" - For Each match As Match In Regex.Matches(input2, lazypattern) - Console.WriteLine("Account ending in ******{0}.", match.Groups(1).Value) - Next - ' The example displays the following output: - ' Account ending in ******3333. - ' Account ending in ******1999. - ' - End Sub + Public Sub Main() + ' + Dim greedyPattern As String = "\b.*([0-9]{4})\b" + Dim input1 As String = "1112223333 3992991999" + For Each match As Match In Regex.Matches(input1, greedypattern) + Console.WriteLine("Account ending in ******{0}.", match.Groups(1).Value) + Next + ' The example displays the following output: + ' Account ending in ******1999. + ' + Console.WriteLine() + ' + Dim lazyPattern As String = "\b.*?([0-9]{4})\b" + Dim input2 As String = "1112223333 3992991999" + For Each match As Match In Regex.Matches(input2, lazypattern) + Console.WriteLine("Account ending in ******{0}.", match.Groups(1).Value) + Next + ' The example displays the following output: + ' Account ending in ******3333. + ' Account ending in ******1999. + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Quantifiers/vb/Quantifiers1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Quantifiers/vb/Quantifiers1.vb index a4d0d0d9b1049..b567750803979 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Quantifiers/vb/Quantifiers1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/RegularExpressions.Quantifiers/vb/Quantifiers1.vb @@ -5,226 +5,226 @@ Imports System.Text.RegularExpressions Module modMain - Public Sub Main() - Console.WriteLine("* quantifier:") - ShowStar() - Console.WriteLine() - Console.WriteLine("+ quantifier:") - ShowPlus() - Console.WriteLine() - Console.WriteLine("? quantifier:") - ShowQuestion() - Console.WriteLine() - Console.WriteLine("{n} quantifier:") - ShowN() - Console.WriteLine() - Console.WriteLine("{n,} quantifier:") - ShowNComma() - Console.WriteLine() - Console.WriteLine("{n,m} quantifier:") - ShowNM() - Console.WriteLine() - Console.WriteLine("*? quantifier:") - ShowLazyStar() - Console.WriteLine() - Console.WriteLine("+? quantifier:") - ShowLazyPlus() - Console.WriteLine() - Console.WriteLine("?? quantifier:") - ShowLazyQuestion() - Console.WriteLine() - Console.WriteLine("{n}? quantifier:") - ShowLazyN() - Console.WriteLine() - Console.WriteLine("{n,}? quantifier: NO EXAMPLE") - ShowLazyNComma() - Console.WriteLine() - Console.WriteLine("{n,m}? quantifier:") - ShowLazyNM() - End Sub - - Private Sub ShowStar() - ' - Dim pattern As String = "\b91*9*\b" - Dim input As String = "99 95 919 929 9119 9219 999 9919 91119" - For Each match As Match In Regex.Matches(input, pattern) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) - Next - ' The example displays the following output: - ' '99' found at position 0. - ' '919' found at position 6. - ' '9119' found at position 14. - ' '999' found at position 24. - ' '91119' found at position 33. - ' - End Sub - - Private Sub ShowPlus() - ' - Dim pattern As String = "\ban+\w*?\b" - - Dim input As String = "Autumn is a great time for an annual announcement to all antique collectors." - For Each match As Match In Regex.Matches(input, pattern, RegexOptions.IgnoreCase) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) - Next - ' The example displays the following output: - ' 'an' found at position 27. - ' 'annual' found at position 30. - ' 'announcement' found at position 37. - ' 'antique' found at position 57. - ' - End Sub - - Private Sub ShowQuestion() - ' - Dim pattern As String = "\ban?\b" - Dim input As String = "An amiable animal with a large snount and an animated nose." - For Each match As Match In Regex.Matches(input, pattern, RegexOptions.IgnoreCase) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) - Next - ' The example displays the following output: - ' 'An' found at position 0. - ' 'a' found at position 23. - ' 'an' found at position 42. - ' - End Sub - - Private Sub ShowN() - ' - Dim pattern As String = "\b\d+\,\d{3}\b" - Dim input As String = "Sales totaled 103,524 million in January, " + _ - "106,971 million in February, but only " + _ - "943 million in March." - For Each match As Match In Regex.Matches(input, pattern) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) - Next - ' The example displays the following output: - ' '103,524' found at position 14. - ' '106,971' found at position 45. - ' - End Sub - - Private Sub ShowNComma() - ' - Dim pattern As String = "\b\d{2,}\b\D+" - Dim input As String = "7 days, 10 weeks, 300 years" - For Each match As Match In Regex.Matches(input, pattern) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) - Next - ' The example displays the following output: - ' '10 weeks, ' found at position 8. - ' '300 years' found at position 18. - ' - End Sub - - Private Sub ShowNM() - ' - Dim pattern As String = "(00\s){2,4}" - Dim input As String = "0x00 FF 00 00 18 17 FF 00 00 00 21 00 00 00 00 00" - For Each match As Match In Regex.Matches(input, pattern) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) - Next - ' The example displays the following output: - ' '00 00 ' found at position 8. - ' '00 00 00 ' found at position 23. - ' '00 00 00 00 ' found at position 35. - ' - End Sub - - Private Sub ShowLazyStar() - ' - Dim pattern As String = "\b\w*?oo\w*?\b" - Dim input As String = "woof root root rob oof woo woe" - For Each match As Match In Regex.Matches(input, pattern, RegexOptions.IgnoreCase) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) - Next - ' The example displays the following output: - ' 'woof' found at position 0. - ' 'root' found at position 5. - ' 'root' found at position 10. - ' 'oof' found at position 19. - ' 'woo' found at position 23. - ' - End Sub - - Private Sub ShowLazyPlus() - ' - Dim pattern As String = "\b\w+?\b" - Dim input As String = "Aa Bb Cc Dd Ee Ff" - For Each match As Match In Regex.Matches(input, pattern) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) - Next - ' The example displays the following output: - ' 'Aa' found at position 0. - ' 'Bb' found at position 3. - ' 'Cc' found at position 6. - ' 'Dd' found at position 9. - ' 'Ee' found at position 12. - ' 'Ff' found at position 15. - ' - End Sub - - Private Sub ShowLazyQuestion() - ' - Dim pattern As String = "^\s*(System.)??Console.Write(Line)??\(??" - Dim input As String = "System.Console.WriteLine(""Hello!"")" + vbCrLf + _ - "Console.Write(""Hello!"")" + vbCrLf + _ - "Console.WriteLine(""Hello!"")" + vbCrLf + _ - "Console.ReadLine()" + vbCrLf + _ - " Console.WriteLine" - For Each match As Match In Regex.Matches(input, pattern, _ - RegexOptions.IgnorePatternWhitespace Or RegexOptions.IgnoreCase Or RegexOptions.MultiLine) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) - Next - ' The example displays the following output: - ' 'System.Console.Write' found at position 0. - ' 'Console.Write' found at position 36. - ' 'Console.Write' found at position 61. - ' ' Console.Write' found at position 110. - ' - End Sub - - Private Sub ShowLazyN() - ' - Dim pattern As String = "\b(\w{3,}?\.){2}?\w{3,}?\b" - Dim input As String = "www.microsoft.com msdn.microsoft.com mywebsite mycompany.com" - For Each match As Match In Regex.Matches(input, pattern) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) - Next - ' The example displays the following output: - ' 'www.microsoft.com' found at position 0. - ' 'msdn.microsoft.com' found at position 18. - ' - End Sub - - Private Sub ShowLazyNComma() - ' -' Dim pattern As String = "\b\d{2,}\b\D+" -' Dim input As String = "7 days, 10 weeks, 300 years" -' For Each match As Match In Regex.Matches(input, pattern) -' Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) -' Next -' ' The example displays the following output: -' ' '10 weeks, ' found at position 8. -' ' '300 years' found at position 18. - ' - End Sub - - Private Sub ShowLazyNM() - ' - Dim pattern As String = "\b[A-Z](\w*\s?){1,10}?[.!?]" - Dim input As String = "Hi. I am writing a short note. Its purpose is " + _ - "to test a regular expression that attempts to find " + _ - "sentences with ten or fewer words. Most sentences " + _ - "in this note are short." - For Each match As Match In Regex.Matches(input, pattern) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) - Next - ' The example displays the following output: - ' 'Hi.' found at position 0. - ' 'I am writing a short note.' found at position 4. - ' 'Most sentences in this note are short.' found at position 132. - ' - End Sub + Public Sub Main() + Console.WriteLine("* quantifier:") + ShowStar() + Console.WriteLine() + Console.WriteLine("+ quantifier:") + ShowPlus() + Console.WriteLine() + Console.WriteLine("? quantifier:") + ShowQuestion() + Console.WriteLine() + Console.WriteLine("{n} quantifier:") + ShowN() + Console.WriteLine() + Console.WriteLine("{n,} quantifier:") + ShowNComma() + Console.WriteLine() + Console.WriteLine("{n,m} quantifier:") + ShowNM() + Console.WriteLine() + Console.WriteLine("*? quantifier:") + ShowLazyStar() + Console.WriteLine() + Console.WriteLine("+? quantifier:") + ShowLazyPlus() + Console.WriteLine() + Console.WriteLine("?? quantifier:") + ShowLazyQuestion() + Console.WriteLine() + Console.WriteLine("{n}? quantifier:") + ShowLazyN() + Console.WriteLine() + Console.WriteLine("{n,}? quantifier: NO EXAMPLE") + ShowLazyNComma() + Console.WriteLine() + Console.WriteLine("{n,m}? quantifier:") + ShowLazyNM() + End Sub + + Private Sub ShowStar() + ' + Dim pattern As String = "\b91*9*\b" + Dim input As String = "99 95 919 929 9119 9219 999 9919 91119" + For Each match As Match In Regex.Matches(input, pattern) + Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) + Next + ' The example displays the following output: + ' '99' found at position 0. + ' '919' found at position 6. + ' '9119' found at position 14. + ' '999' found at position 24. + ' '91119' found at position 33. + ' + End Sub + + Private Sub ShowPlus() + ' + Dim pattern As String = "\ban+\w*?\b" + + Dim input As String = "Autumn is a great time for an annual announcement to all antique collectors." + For Each match As Match In Regex.Matches(input, pattern, RegexOptions.IgnoreCase) + Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) + Next + ' The example displays the following output: + ' 'an' found at position 27. + ' 'annual' found at position 30. + ' 'announcement' found at position 37. + ' 'antique' found at position 57. + ' + End Sub + + Private Sub ShowQuestion() + ' + Dim pattern As String = "\ban?\b" + Dim input As String = "An amiable animal with a large snount and an animated nose." + For Each match As Match In Regex.Matches(input, pattern, RegexOptions.IgnoreCase) + Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) + Next + ' The example displays the following output: + ' 'An' found at position 0. + ' 'a' found at position 23. + ' 'an' found at position 42. + ' + End Sub + + Private Sub ShowN() + ' + Dim pattern As String = "\b\d+\,\d{3}\b" + Dim input As String = "Sales totaled 103,524 million in January, " + _ + "106,971 million in February, but only " + _ + "943 million in March." + For Each match As Match In Regex.Matches(input, pattern) + Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) + Next + ' The example displays the following output: + ' '103,524' found at position 14. + ' '106,971' found at position 45. + ' + End Sub + + Private Sub ShowNComma() + ' + Dim pattern As String = "\b\d{2,}\b\D+" + Dim input As String = "7 days, 10 weeks, 300 years" + For Each match As Match In Regex.Matches(input, pattern) + Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) + Next + ' The example displays the following output: + ' '10 weeks, ' found at position 8. + ' '300 years' found at position 18. + ' + End Sub + + Private Sub ShowNM() + ' + Dim pattern As String = "(00\s){2,4}" + Dim input As String = "0x00 FF 00 00 18 17 FF 00 00 00 21 00 00 00 00 00" + For Each match As Match In Regex.Matches(input, pattern) + Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) + Next + ' The example displays the following output: + ' '00 00 ' found at position 8. + ' '00 00 00 ' found at position 23. + ' '00 00 00 00 ' found at position 35. + ' + End Sub + + Private Sub ShowLazyStar() + ' + Dim pattern As String = "\b\w*?oo\w*?\b" + Dim input As String = "woof root root rob oof woo woe" + For Each match As Match In Regex.Matches(input, pattern, RegexOptions.IgnoreCase) + Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) + Next + ' The example displays the following output: + ' 'woof' found at position 0. + ' 'root' found at position 5. + ' 'root' found at position 10. + ' 'oof' found at position 19. + ' 'woo' found at position 23. + ' + End Sub + + Private Sub ShowLazyPlus() + ' + Dim pattern As String = "\b\w+?\b" + Dim input As String = "Aa Bb Cc Dd Ee Ff" + For Each match As Match In Regex.Matches(input, pattern) + Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) + Next + ' The example displays the following output: + ' 'Aa' found at position 0. + ' 'Bb' found at position 3. + ' 'Cc' found at position 6. + ' 'Dd' found at position 9. + ' 'Ee' found at position 12. + ' 'Ff' found at position 15. + ' + End Sub + + Private Sub ShowLazyQuestion() + ' + Dim pattern As String = "^\s*(System.)??Console.Write(Line)??\(??" + Dim input As String = "System.Console.WriteLine(""Hello!"")" + vbCrLf + _ + "Console.Write(""Hello!"")" + vbCrLf + _ + "Console.WriteLine(""Hello!"")" + vbCrLf + _ + "Console.ReadLine()" + vbCrLf + _ + " Console.WriteLine" + For Each match As Match In Regex.Matches(input, pattern, _ + RegexOptions.IgnorePatternWhitespace Or RegexOptions.IgnoreCase Or RegexOptions.MultiLine) + Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) + Next + ' The example displays the following output: + ' 'System.Console.Write' found at position 0. + ' 'Console.Write' found at position 36. + ' 'Console.Write' found at position 61. + ' ' Console.Write' found at position 110. + ' + End Sub + + Private Sub ShowLazyN() + ' + Dim pattern As String = "\b(\w{3,}?\.){2}?\w{3,}?\b" + Dim input As String = "www.microsoft.com msdn.microsoft.com mywebsite mycompany.com" + For Each match As Match In Regex.Matches(input, pattern) + Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) + Next + ' The example displays the following output: + ' 'www.microsoft.com' found at position 0. + ' 'msdn.microsoft.com' found at position 18. + ' + End Sub + + Private Sub ShowLazyNComma() + ' + ' Dim pattern As String = "\b\d{2,}\b\D+" + ' Dim input As String = "7 days, 10 weeks, 300 years" + ' For Each match As Match In Regex.Matches(input, pattern) + ' Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) + ' Next + ' ' The example displays the following output: + ' ' '10 weeks, ' found at position 8. + ' ' '300 years' found at position 18. + ' + End Sub + + Private Sub ShowLazyNM() + ' + Dim pattern As String = "\b[A-Z](\w*\s?){1,10}?[.!?]" + Dim input As String = "Hi. I am writing a short note. Its purpose is " + _ + "to test a regular expression that attempts to find " + _ + "sentences with ten or fewer words. Most sentences " + _ + "in this note are short." + For Each match As Match In Regex.Matches(input, pattern) + Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index) + Next + ' The example displays the following output: + ' 'Hi.' found at position 0. + ' 'I am writing a short note.' found at position 4. + ' 'Most sentences in this note are short.' found at position 132. + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/SetCurrentPrincipal/VB/program.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/SetCurrentPrincipal/VB/program.vb index eb7be962d446d..821563f169094 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/SetCurrentPrincipal/VB/program.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/SetCurrentPrincipal/VB/program.vb @@ -70,4 +70,4 @@ Class SecurityPrincipalDemo End Class -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Strings.ChangingCase/vb/Example.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Strings.ChangingCase/vb/Example.vb index 7ab92ee8d927d..b7720a48bc77e 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Strings.ChangingCase/vb/Example.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Strings.ChangingCase/vb/Example.vb @@ -3,28 +3,28 @@ Option Strict On Module Example - Public Sub Main() - ConvertToUpperCase() - Console.WriteLine() - ConvertToLowerCase() - End Sub - - Private Sub ConvertToUpperCase() - ' - Dim MyString As String = "Hello World!" - Console.WriteLine(MyString.ToUpper()) - ' This example displays the following output: - ' HELLO WORLD! - ' - End Sub - - Private Sub ConvertToLowerCase() - ' - Dim MyString As String = "Hello World!" - Console.WriteLine(MyString.ToLower()) - ' This example displays the following output: - ' hello world! - ' - End Sub + Public Sub Main() + ConvertToUpperCase() + Console.WriteLine() + ConvertToLowerCase() + End Sub + + Private Sub ConvertToUpperCase() + ' + Dim MyString As String = "Hello World!" + Console.WriteLine(MyString.ToUpper()) + ' This example displays the following output: + ' HELLO WORLD! + ' + End Sub + + Private Sub ConvertToLowerCase() + ' + Dim MyString As String = "Hello World!" + Console.WriteLine(MyString.ToLower()) + ' This example displays the following output: + ' hello world! + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/Strings.Creating/vb/Example.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/Strings.Creating/vb/Example.vb index a1f631c087b75..bcdbbea7075f4 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/Strings.Creating/vb/Example.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/Strings.Creating/vb/Example.vb @@ -4,71 +4,71 @@ Option Strict On Module Example - Public Sub Main() - UseStringFormat() - Console.WriteLine() - UseStringConcat() - Console.WriteLine() - UseStringJoin() - Console.WriteLine() - UseStringInsert() - Console.WriteLine() - UseStringCopyTo() - End Sub - - Private Sub UseStringFormat() - ' - Dim numberOfFleas As Integer = 12 - Dim miscInfo As String = String.Format("Your dog has {0} fleas. " & _ - "It is time to get a flea collar. " & _ - "The current universal date is: {1:u}.", _ - numberOfFleas, Date.Now) - Console.WriteLine(miscInfo) - ' The example displays the following output: - ' Your dog has 12 fleas. It is time to get a flea collar. - ' The current universal date is: 2008-03-28 13:31:40Z. - ' - End Sub - - Private Sub UseStringConcat() - ' - Dim helloString1 As String = "Hello" - Dim helloString2 As String = "World!" - Console.WriteLine(String.Concat(helloString1, " "c, helloString2)) - ' The example displays the following output: - ' Hello World! - ' - End Sub + Public Sub Main() + UseStringFormat() + Console.WriteLine() + UseStringConcat() + Console.WriteLine() + UseStringJoin() + Console.WriteLine() + UseStringInsert() + Console.WriteLine() + UseStringCopyTo() + End Sub - Private Sub UseStringJoin() - ' - Dim words() As String = {"Hello", "and", "welcome", "to", "my" , "world!"} - Console.WriteLine(String.Join(" ", words)) - ' The example displays the following output: - ' Hello and welcome to my world! - ' - End Sub + Private Sub UseStringFormat() + ' + Dim numberOfFleas As Integer = 12 + Dim miscInfo As String = String.Format("Your dog has {0} fleas. " & _ + "It is time to get a flea collar. " & _ + "The current universal date is: {1:u}.", _ + numberOfFleas, Date.Now) + Console.WriteLine(miscInfo) + ' The example displays the following output: + ' Your dog has 12 fleas. It is time to get a flea collar. + ' The current universal date is: 2008-03-28 13:31:40Z. + ' + End Sub - Private Sub UseStringInsert() - ' - Dim sentence As String = "Once a time." - Console.WriteLine(sentence.Insert(4, " upon")) - ' The example displays the following output: - ' Once upon a time. - ' - End Sub + Private Sub UseStringConcat() + ' + Dim helloString1 As String = "Hello" + Dim helloString2 As String = "World!" + Console.WriteLine(String.Concat(helloString1, " "c, helloString2)) + ' The example displays the following output: + ' Hello World! + ' + End Sub - Private Sub UseStringCopyTo() - ' - Dim greeting As String = "Hello World!" - Dim charArray() As Char = {"W"c, "h"c, "e"c, "r"c, "e"c} - Console.WriteLine("The original character array: {0}", New String(charArray)) - greeting.CopyTo(0, charArray,0 ,5) - Console.WriteLine("The new character array: {0}", New String(charArray)) - ' The example displays the following output: - ' The original character array: Where - ' The new character array: Hello - ' - End Sub + Private Sub UseStringJoin() + ' + Dim words() As String = {"Hello", "and", "welcome", "to", "my", "world!"} + Console.WriteLine(String.Join(" ", words)) + ' The example displays the following output: + ' Hello and welcome to my world! + ' + End Sub + + Private Sub UseStringInsert() + ' + Dim sentence As String = "Once a time." + Console.WriteLine(sentence.Insert(4, " upon")) + ' The example displays the following output: + ' Once upon a time. + ' + End Sub + + Private Sub UseStringCopyTo() + ' + Dim greeting As String = "Hello World!" + Dim charArray() As Char = {"W"c, "h"c, "e"c, "r"c, "e"c} + Console.WriteLine("The original character array: {0}", New String(charArray)) + greeting.CopyTo(0, charArray, 0, 5) + Console.WriteLine("The new character array: {0}", New String(charArray)) + ' The example displays the following output: + ' The original character array: Where + ' The new character array: Hello + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/TimeZone2.Serialization/vb/SerializeTimeZoneData.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/TimeZone2.Serialization/vb/SerializeTimeZoneData.vb index eb4f1a52557b6..a5cf2832de880 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/TimeZone2.Serialization/vb/SerializeTimeZoneData.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/TimeZone2.Serialization/vb/SerializeTimeZoneData.vb @@ -6,114 +6,114 @@ Imports System.Resources '
Module SerializeTimeZoneData - Private Const resxName As String = "SerializedTimeZones.resx" + Private Const resxName As String = "SerializedTimeZones.resx" - Sub Main() - If MsgBox("Serialize time zones?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then - SerializeTimeZones() - End If - If MsgBox("Deserialize time zones?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then - DeserializeTimeZones() - End If - End Sub + Sub Main() + If MsgBox("Serialize time zones?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then + SerializeTimeZones() + End If + If MsgBox("Deserialize time zones?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then + DeserializeTimeZones() + End If + End Sub - ' - Private Sub SerializeTimeZones() - Dim writeStream As TextWriter - Dim resources As New Dictionary(Of String, String) - ' Determine if .resx file exists - If File.Exists(resxName) Then - ' Open reader - Dim readStream As TextReader = New StreamReader(resxName) - Dim resReader As New ResXResourceReader(readStream) - For Each item As DictionaryEntry In resReader - If Not (CStr(item.Key) = "CentralStandardTime" Or _ - CStr(item.Key) = "PalmerStandardTime") Then - resources.Add(CStr(item.Key), CStr(item.Value)) - End If - Next - readStream.Close() - ' Delete file, since write method creates duplicate xml headers - File.Delete(resxName) - End If + ' + Private Sub SerializeTimeZones() + Dim writeStream As TextWriter + Dim resources As New Dictionary(Of String, String) + ' Determine if .resx file exists + If File.Exists(resxName) Then + ' Open reader + Dim readStream As TextReader = New StreamReader(resxName) + Dim resReader As New ResXResourceReader(readStream) + For Each item As DictionaryEntry In resReader + If Not (CStr(item.Key) = "CentralStandardTime" Or _ + CStr(item.Key) = "PalmerStandardTime") Then + resources.Add(CStr(item.Key), CStr(item.Value)) + End If + Next + readStream.Close() + ' Delete file, since write method creates duplicate xml headers + File.Delete(resxName) + End If - ' Open stream to write to .resx file - Try - writeStream = New StreamWriter(resxName, True) - Catch e As FileNotFoundException - ' Handle failure to find file - Console.WriteLine("{0}: The file {1} could not be found.", e.GetType().Name, resxName) - Exit Sub - End Try + ' Open stream to write to .resx file + Try + writeStream = New StreamWriter(resxName, True) + Catch e As FileNotFoundException + ' Handle failure to find file + Console.WriteLine("{0}: The file {1} could not be found.", e.GetType().Name, resxName) + Exit Sub + End Try - ' Get resource writer - Dim resWriter As ResXResourceWriter = New ResXResourceWriter(writeStream) + ' Get resource writer + Dim resWriter As ResXResourceWriter = New ResXResourceWriter(writeStream) - ' Add resources from existing file - For Each item As KeyValuePair(Of String, String) In resources - resWriter.AddResource(item.Key, item.Value) - Next - ' Serialize Central Standard Time - Try - Dim cst As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time") - resWriter.AddResource(cst.Id.Replace(" ", String.Empty), cst.ToSerializedString()) - Catch - Console.WriteLine("The Central Standard Time zone could not be found.") - End Try + ' Add resources from existing file + For Each item As KeyValuePair(Of String, String) In resources + resWriter.AddResource(item.Key, item.Value) + Next + ' Serialize Central Standard Time + Try + Dim cst As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time") + resWriter.AddResource(cst.Id.Replace(" ", String.Empty), cst.ToSerializedString()) + Catch + Console.WriteLine("The Central Standard Time zone could not be found.") + End Try - ' Create time zone for Palmer, Antarctica - ' - ' Define transition times to/from DST - Dim startTransition As TimeZoneInfo.TransitionTime = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(#4:00:00 AM#, 10, 2, DayOfWeek.Sunday) - Dim endTransition As TimeZoneInfo.TransitionTime = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(#3:00:00 AM#, 3, 2, DayOfWeek.Sunday) - ' Define adjustment rule - Dim delta As TimeSpan = New TimeSpan(1, 0, 0) - Dim adjustment As TimeZoneInfo.AdjustmentRule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(#10/1/1999#, Date.MaxValue.Date, delta, startTransition, endTransition) - ' Create array for adjustment rules - Dim adjustments() As TimeZoneInfo.AdjustmentRule = {adjustment} - ' Define other custom time zone arguments - Dim DisplayName As String = "(GMT-04:00) Antarctica/Palmer Time" - Dim standardName As String = "Palmer Standard Time" - Dim daylightName As String = "Palmer Daylight Time" - Dim offset As TimeSpan = New TimeSpan(-4, 0, 0) - Dim palmer As TimeZoneInfo = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, DisplayName, standardName, daylightName, adjustments) - resWriter.AddResource(palmer.Id.Replace(" ", String.Empty), palmer.ToSerializedString()) + ' Create time zone for Palmer, Antarctica + ' + ' Define transition times to/from DST + Dim startTransition As TimeZoneInfo.TransitionTime = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(#4:00:00 AM#, 10, 2, DayOfWeek.Sunday) + Dim endTransition As TimeZoneInfo.TransitionTime = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(#3:00:00 AM#, 3, 2, DayOfWeek.Sunday) + ' Define adjustment rule + Dim delta As TimeSpan = New TimeSpan(1, 0, 0) + Dim adjustment As TimeZoneInfo.AdjustmentRule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(#10/1/1999#, Date.MaxValue.Date, delta, startTransition, endTransition) + ' Create array for adjustment rules + Dim adjustments() As TimeZoneInfo.AdjustmentRule = {adjustment} + ' Define other custom time zone arguments + Dim DisplayName As String = "(GMT-04:00) Antarctica/Palmer Time" + Dim standardName As String = "Palmer Standard Time" + Dim daylightName As String = "Palmer Daylight Time" + Dim offset As TimeSpan = New TimeSpan(-4, 0, 0) + Dim palmer As TimeZoneInfo = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, DisplayName, standardName, daylightName, adjustments) + resWriter.AddResource(palmer.Id.Replace(" ", String.Empty), palmer.ToSerializedString()) - ' Save changes to .resx file - resWriter.Generate() - resWriter.Close() - writeStream.Close() - End Sub - ' + ' Save changes to .resx file + resWriter.Generate() + resWriter.Close() + writeStream.Close() + End Sub + ' - ' - Private Sub DeserializeTimeZones() - Dim cst, palmer As TimeZoneInfo - Dim timeZoneString As String - Dim resMgr As ResourceManager = New ResourceManager("SerializeTimeZoneData.SerializedTimeZones", - GetType(SerializeTimeZoneData).Assembly) + ' + Private Sub DeserializeTimeZones() + Dim cst, palmer As TimeZoneInfo + Dim timeZoneString As String + Dim resMgr As ResourceManager = New ResourceManager("SerializeTimeZoneData.SerializedTimeZones", + GetType(SerializeTimeZoneData).Assembly) - ' Attempt to retrieve time zone from system - Try - cst = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time") - Catch ex As TimeZoneNotFoundException - ' Time zone not in system; retrieve from resource - timeZoneString = resMgr.GetString("CentralStandardTime") - If Not String.IsNullOrEmpty(timeZoneString) Then - cst = TimeZoneInfo.FromSerializedString(timeZoneString) - Else - MsgBox("Unable to create Central Standard Time Zone. Application must exit.") + ' Attempt to retrieve time zone from system + Try + cst = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time") + Catch ex As TimeZoneNotFoundException + ' Time zone not in system; retrieve from resource + timeZoneString = resMgr.GetString("CentralStandardTime") + If Not String.IsNullOrEmpty(timeZoneString) Then + cst = TimeZoneInfo.FromSerializedString(timeZoneString) + Else + MsgBox("Unable to create Central Standard Time Zone. Application must exit.") + Exit Sub + End If + End Try + ' Retrieve custom time zone + Try + timeZoneString = resMgr.GetString("PalmerStandardTime") + palmer = TimeZoneInfo.FromSerializedString(timeZoneString) + Catch ex As Exception + MsgBox(ex.GetType().Name & ": Unable to create Palmer Standard Time Zone. Application must exit.") Exit Sub - End If - End Try - ' Retrieve custom time zone - Try - timeZoneString = resMgr.GetString("PalmerStandardTime") - palmer = TimeZoneInfo.FromSerializedString(timeZoneString) - Catch ex As Exception - MsgBox(ex.GetType().Name & ": Unable to create Palmer Standard Time Zone. Application must exit.") - Exit Sub - End Try - End Sub - ' + End Try + End Sub + ' End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/appcompat.ignoreemptykeysequences/vb/module1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/appcompat.ignoreemptykeysequences/vb/module1.vb index fec687f936660..e23bda6d02d8c 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/appcompat.ignoreemptykeysequences/vb/module1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/appcompat.ignoreemptykeysequences/vb/module1.vb @@ -1,13 +1,13 @@ Module Module1 - Sub Main() - ' - ' Ignore empty key sequences in apps that target .NET 4.6 - AppContext.SetSwitch("System.Xml.IgnoreEmptyKeySequences", True) - ' + Sub Main() + ' + ' Ignore empty key sequences in apps that target .NET 4.6 + AppContext.SetSwitch("System.Xml.IgnoreEmptyKeySequences", True) + ' - ' - ' Do Not ignore empty key sequences in apps that target .NET 4.5.1 And earlier - AppContext.SetSwitch("System.Xml.IgnoreEmptyKeySequences", False) - ' - End Sub + ' + ' Do Not ignore empty key sequences in apps that target .NET 4.5.1 And earlier + AppContext.SetSwitch("System.Xml.IgnoreEmptyKeySequences", False) + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/appcompat.sslprotocols/vb/module1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/appcompat.sslprotocols/vb/module1.vb index e3496239910d0..5eac008afa10f 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/appcompat.sslprotocols/vb/module1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/appcompat.sslprotocols/vb/module1.vb @@ -1,12 +1,12 @@ Module Module1 - Sub Main() - ' - Const DisableCachingName As String = "TestSwitch.LocalAppContext.DisableCaching" - Const DontEnableSchUseStrongCryptoName As String = "Switch.System.Net.DontEnableSchUseStrongCrypto" - AppContext.SetSwitch(DisableCachingName, True) - AppContext.SetSwitch(DontEnableSchUseStrongCryptoName, True) - ' - End Sub + Sub Main() + ' + Const DisableCachingName As String = "TestSwitch.LocalAppContext.DisableCaching" + Const DontEnableSchUseStrongCryptoName As String = "Switch.System.Net.DontEnableSchUseStrongCrypto" + AppContext.SetSwitch(DisableCachingName, True) + AppContext.SetSwitch(DontEnableSchUseStrongCryptoName, True) + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/cocontrasimpleaction/vb/example.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/cocontrasimpleaction/vb/example.vb index 4d2b0a9158196..4a2eba54d61ae 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/cocontrasimpleaction/vb/example.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/cocontrasimpleaction/vb/example.vb @@ -8,7 +8,7 @@ End Class Class Example Shared Sub Main() ' - Dim b As Action(Of Base) = Sub(target As Base) + Dim b As Action(Of Base) = Sub(target As Base) Console.WriteLine(target.GetType().Name) End Sub Dim d As Action(Of Derived) = b diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/cocontrasimpleienum/vb/example.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/cocontrasimpleienum/vb/example.vb index 9f62713c6a8a1..12f3a6af4e3fc 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/cocontrasimpleienum/vb/example.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/cocontrasimpleienum/vb/example.vb @@ -13,4 +13,4 @@ Class C Dim b As IEnumerable(Of Base) = d ' End Sub -End Class \ No newline at end of file +End Class diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravariancedelegates/vb/example.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravariancedelegates/vb/example.vb index 1897f56dd5268..1ff4f24b8a65c 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravariancedelegates/vb/example.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravariancedelegates/vb/example.vb @@ -1,37 +1,37 @@ ' ' -Public Class Base +Public Class Base End Class Public Class Derived Inherits Base End Class Public Class Program - Public Shared Function MyMethod(ByVal b As Base) As Derived + Public Shared Function MyMethod(ByVal b As Base) As Derived Return If(TypeOf b Is Derived, b, New Derived()) End Function - Shared Sub Main() + Shared Sub Main() Dim f1 As Func(Of Base, Derived) = AddressOf MyMethod -' + '
-' + ' ' Covariant return type. Dim f2 As Func(Of Base, Base) = f1 Dim b2 As Base = f2(New Base()) -' + ' -' + ' ' Contravariant parameter type. Dim f3 As Func(Of Derived, Derived) = f1 Dim d3 As Derived = f3(New Derived()) -' + ' -' + ' ' Covariant return type and contravariant parameter type. Dim f4 As Func(Of Derived, Base) = f1 Dim b4 As Base = f4(New Derived()) -' + ' End Sub End Class ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravariancedelegatesgenrelaxed/vb/example.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravariancedelegatesgenrelaxed/vb/example.vb index 0ef515aa916a2..dca41ae51fe47 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravariancedelegatesgenrelaxed/vb/example.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravariancedelegatesgenrelaxed/vb/example.vb @@ -1,5 +1,5 @@ ' -Public Class Type1 +Public Class Type1 End Class Public Class Type2 Inherits Type1 @@ -13,7 +13,7 @@ Public Class Program Return If(TypeOf t Is Type3, t, New Type3()) End Function - Shared Sub Main() + Shared Sub Main() Dim f1 As Func(Of Type2, Type2) = AddressOf MyMethod ' Covariant return type and contravariant parameter type. diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravarianceinclrgenerici/vb/example.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravarianceinclrgenerici/vb/example.vb index cd4dae9c77476..128dfec47a20d 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravarianceinclrgenerici/vb/example.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravarianceinclrgenerici/vb/example.vb @@ -6,7 +6,7 @@ Class Base For Each b As Base In bases Console.WriteLine(b) Next - End Sub + End Sub End Class Class Derived diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravarianceinclrgenerici2/vb/example.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravarianceinclrgenerici2/vb/example.vb index d40413162dbe9..02a81d9e8a601 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravarianceinclrgenerici2/vb/example.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/cocontravarianceinclrgenerici2/vb/example.vb @@ -8,10 +8,10 @@ End Class Class Circle Inherits Shape - Private r As Double + Private r As Double Public Sub New(ByVal radius As Double) r = radius - End Sub + End Sub Public ReadOnly Property Radius As Double Get Return r @@ -41,7 +41,7 @@ Class Program ' IComparer(Of Circle), because type parameter T of IComparer(Of T) ' is contravariant. Dim circlesByArea As New SortedSet(Of Circle)(New ShapeAreaComparer()) _ - From { New Circle(7.2), New Circle(100), Nothing, New Circle(.01) } + From {New Circle(7.2), New Circle(100), Nothing, New Circle(.01)} For Each c As Circle In circlesByArea Console.WriteLine(If(c Is Nothing, "Nothing", "Circle with area " & c.Area)) diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source1.vb index a3f6ba6891680..6e19cb009cefd 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source1.vb @@ -1,7 +1,7 @@ ' ' Imports System.Reflection - + ' ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb index 8c84fa3f20ba1..82b120cb3c0b7 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb @@ -51,7 +51,7 @@ End Namespace Namespace CustomCodeAttributes_Examples1 ' - + Public Class SomeClass Inherits Attribute '... @@ -73,7 +73,7 @@ Namespace CustomCodeAttributes_Examples1 '... End Class - + Public Class YourAttribute Inherits Attribute '... @@ -109,13 +109,13 @@ Namespace CustomCodeAttributes_Examples2 Inherits Attribute End Class - + Public Class YourAttribute Inherits Attribute End Class ' -' #if'd out since MyClass will intentionally not compile + ' #if'd out since MyClass will intentionally not compile #If False ' @@ -172,7 +172,7 @@ Namespace CustomCodeAttributes_Examples4 ' Public Property MyProperty As Boolean Get - Return Me.myvalue + Return Me.myvalue End Get Set Me.myvalue = Value @@ -182,7 +182,7 @@ Namespace CustomCodeAttributes_Examples4 Public Property OptionalParameter As String Get - Return Me.myoptional + Return Me.myoptional End Get Set Me.myoptional = Value @@ -192,7 +192,7 @@ Namespace CustomCodeAttributes_Examples4 ' ' One required (positional) and one optional (named) parameter are applied. - + Public Class SomeClass '... End Class diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source3.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source3.vb index 1a5784513fe4c..7803095d528f0 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source3.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source3.vb @@ -2,7 +2,7 @@ Imports System.Reflection Imports CustomCodeAttributes - + Class MainApp Public Shared Sub Main() ' Call function to get and display the attribute. @@ -18,11 +18,11 @@ Class MainApp Console.WriteLine("The attribute was not found.") Else ' Get the Name value. - Console.WriteLine("The Name Attribute is: {0}." , MyAttribute.Name) + Console.WriteLine("The Name Attribute is: {0}.", MyAttribute.Name) ' Get the Level value. - Console.WriteLine("The Level Attribute is: {0}." , MyAttribute.Level) + Console.WriteLine("The Level Attribute is: {0}.", MyAttribute.Level) ' Get the Reviewed value. - Console.WriteLine("The Reviewed Attribute is: {0}." , MyAttribute.Reviewed) + Console.WriteLine("The Reviewed Attribute is: {0}.", MyAttribute.Reviewed) End If End Sub End Class @@ -39,9 +39,9 @@ Class GetAttribTest1 Else For i As Integer = 0 To MyAttributes.Length - 1 ' Get the Name value. - Console.WriteLine("The Name Attribute is: {0}." , MyAttributes(i).Name) + Console.WriteLine("The Name Attribute is: {0}.", MyAttributes(i).Name) ' Get the Level value. - Console.WriteLine("The Level Attribute is: {0}." , MyAttributes(i).Level) + Console.WriteLine("The Level Attribute is: {0}.", MyAttributes(i).Level) ' Get the Reviewed value. Console.WriteLine("The Reviewed Attribute is: {0}.", MyAttributes(i).Reviewed) Next i @@ -80,7 +80,7 @@ Class GetAttribTest2 att = CType(Attribute.GetCustomAttribute(MyMemberInfo(i), _ GetType(DeveloperAttribute)), DeveloperAttribute) If att Is Nothing Then - Console.WriteLine("No attribute in member function {0}.\n" , MyMemberInfo(i).ToString()) + Console.WriteLine("No attribute in member function {0}.\n", MyMemberInfo(i).ToString()) Else Console.WriteLine("The Name Attribute for the {0} member is: {1}.", MyMemberInfo(i).ToString(), att.Name) @@ -92,4 +92,4 @@ Class GetAttribTest2 Next End Sub ' -End Class \ No newline at end of file +End Class diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source2.vb index 23528c2245bde..990bb4008fb37 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source2.vb @@ -18,7 +18,7 @@ Class DirAppend w.WriteLine($"{DateTime.Now.ToLongTimeString()} {DateTime.Now.ToLongDateString()}") w.WriteLine(" :") w.WriteLine($" :{logMessage}") - w.WriteLine ("-------------------------------") + w.WriteLine("-------------------------------") End Sub Public Shared Sub DumpLog(r As StreamReader) diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source4.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source4.vb index 5056b7a915739..ba390ef331229 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source4.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source4.vb @@ -17,7 +17,7 @@ Public Class TextFromFile Console.WriteLine(input) End If Loop Until input Is Nothing - Console.WriteLine ("The end of the stream has been reached.") + Console.WriteLine("The end of the stream has been reached.") End Using End Sub End Class diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source5.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source5.vb index 734d8e599e9a2..279cf5b991608 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source5.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source5.vb @@ -18,7 +18,7 @@ Class MainWindow ' Open a stream writer to a new text file named "UserInputFile.txt" and write the contents ' of the stringbuilder to it. - Using outfile As StreamWriter = New StreamWriter(Path.Combine(mydocpath,"UserInputFile.txt"), True) + Using outfile As StreamWriter = New StreamWriter(Path.Combine(mydocpath, "UserInputFile.txt"), True) Await outfile.WriteAsync(sb.ToString()) End Using End Sub diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source6.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source6.vb index ddfeef214bfd5..cf91530a4de31 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source6.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.basicio.textfiles/vb/source6.vb @@ -14,4 +14,4 @@ Class MainWindow End Try End Sub End Class -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/calendarinfo1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/calendarinfo1.vb index 36fd30f2caa44..7ce0612ce88c1 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/calendarinfo1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/calendarinfo1.vb @@ -5,46 +5,46 @@ Option Strict On Imports System.Globalization Public Module Example - Public Sub Main() - ' Create a CultureInfo for Thai in Thailand. - Dim th As CultureInfo = CultureInfo.CreateSpecificCulture("th-TH") - DisplayCalendars(th) - - ' Create a CultureInfo for Japanese in Japan. - Dim ja As CultureInfo = CultureInfo.CreateSpecificCulture("ja-JP") - DisplayCalendars(ja) - End Sub - - Sub DisplayCalendars(ci As CultureInfo) - Console.WriteLine("Calendars for the {0} culture:", ci.Name) - - ' Get the culture's default calendar. - Dim defaultCalendar As Calendar = ci.Calendar - Console.Write(" Default Calendar: {0}", GetCalendarName(defaultCalendar)) - - If TypeOf defaultCalendar Is GregorianCalendar Then - Console.WriteLine(" ({0})", - CType(defaultCalendar, GregorianCalendar).CalendarType) - Else - Console.WriteLine() - End If - - ' Get the culture's optional calendars. - Console.WriteLine(" Optional Calendars:") - For Each optionalCalendar In ci.OptionalCalendars - Console.Write("{0,6}{1}", "", GetCalendarName(optionalCalendar)) - If TypeOf optionalCalendar Is GregorianCalendar Then - Console.Write(" ({0})", - CType(optionalCalendar, GregorianCalendar).CalendarType) - End If - Console.WriteLine() - Next - Console.WriteLine() - End Sub - - Function GetCalendarName(cal As Calendar) As String - Return cal.ToString().Replace("System.Globalization.", "") - End Function + Public Sub Main() + ' Create a CultureInfo for Thai in Thailand. + Dim th As CultureInfo = CultureInfo.CreateSpecificCulture("th-TH") + DisplayCalendars(th) + + ' Create a CultureInfo for Japanese in Japan. + Dim ja As CultureInfo = CultureInfo.CreateSpecificCulture("ja-JP") + DisplayCalendars(ja) + End Sub + + Sub DisplayCalendars(ci As CultureInfo) + Console.WriteLine("Calendars for the {0} culture:", ci.Name) + + ' Get the culture's default calendar. + Dim defaultCalendar As Calendar = ci.Calendar + Console.Write(" Default Calendar: {0}", GetCalendarName(defaultCalendar)) + + If TypeOf defaultCalendar Is GregorianCalendar Then + Console.WriteLine(" ({0})", + CType(defaultCalendar, GregorianCalendar).CalendarType) + Else + Console.WriteLine() + End If + + ' Get the culture's optional calendars. + Console.WriteLine(" Optional Calendars:") + For Each optionalCalendar In ci.OptionalCalendars + Console.Write("{0,6}{1}", "", GetCalendarName(optionalCalendar)) + If TypeOf optionalCalendar Is GregorianCalendar Then + Console.Write(" ({0})", + CType(optionalCalendar, GregorianCalendar).CalendarType) + End If + Console.WriteLine() + Next + Console.WriteLine() + End Sub + + Function GetCalendarName(cal As Calendar) As String + Return cal.ToString().Replace("System.Globalization.", "") + End Function End Module ' The example displays the following output: ' Calendars for the th-TH culture: diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/changecalendar2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/changecalendar2.vb index 9c1d7e12fba85..3de919e3ad1ab 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/changecalendar2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/changecalendar2.vb @@ -6,47 +6,47 @@ Imports System.Globalization Imports System.Threading Module Example - Public Sub Main() - Dim date1 As Date = #6/20/2011# - - DisplayCurrentInfo() - ' Display the date using the current culture and calendar. - Console.WriteLine(date1.ToString("d")) - Console.WriteLine() - - Dim arSA As CultureInfo = CultureInfo.CreateSpecificCulture("ar-SA") - - ' Change the current culture to Arabic (Saudi Arabia). - Thread.CurrentThread.CurrentCulture = arSA - ' Display date and information about the current culture. - DisplayCurrentInfo() - Console.WriteLine(date1.ToString("d")) - Console.WriteLine() - - ' Change the calendar to Hijri. - Dim hijri As Calendar = New HijriCalendar() - If CalendarExists(arSA, hijri) Then - arSA.DateTimeFormat.Calendar = hijri - ' Display date and information about the current culture. - DisplayCurrentInfo() - Console.WriteLine(date1.ToString("d")) - End If - End Sub - - Private Sub DisplayCurrentInfo() - Console.WriteLine("Current Culture: {0}", - CultureInfo.CurrentCulture.Name) - Console.WriteLine("Current Calendar: {0}", - DateTimeFormatInfo.CurrentInfo.Calendar) - End Sub - - Private Function CalendarExists(ByVal culture As CultureInfo, - cal As Calendar) As Boolean - For Each optionalCalendar As Calendar In culture.OptionalCalendars - If cal.ToString().Equals(optionalCalendar.ToString()) Then Return True - Next - Return False - End Function + Public Sub Main() + Dim date1 As Date = #6/20/2011# + + DisplayCurrentInfo() + ' Display the date using the current culture and calendar. + Console.WriteLine(date1.ToString("d")) + Console.WriteLine() + + Dim arSA As CultureInfo = CultureInfo.CreateSpecificCulture("ar-SA") + + ' Change the current culture to Arabic (Saudi Arabia). + Thread.CurrentThread.CurrentCulture = arSA + ' Display date and information about the current culture. + DisplayCurrentInfo() + Console.WriteLine(date1.ToString("d")) + Console.WriteLine() + + ' Change the calendar to Hijri. + Dim hijri As Calendar = New HijriCalendar() + If CalendarExists(arSA, hijri) Then + arSA.DateTimeFormat.Calendar = hijri + ' Display date and information about the current culture. + DisplayCurrentInfo() + Console.WriteLine(date1.ToString("d")) + End If + End Sub + + Private Sub DisplayCurrentInfo() + Console.WriteLine("Current Culture: {0}", + CultureInfo.CurrentCulture.Name) + Console.WriteLine("Current Calendar: {0}", + DateTimeFormatInfo.CurrentInfo.Calendar) + End Sub + + Private Function CalendarExists(ByVal culture As CultureInfo, + cal As Calendar) As Boolean + For Each optionalCalendar As Calendar In culture.OptionalCalendars + If cal.ToString().Equals(optionalCalendar.ToString()) Then Return True + Next + Return False + End Function End Module ' The example displays the following output: ' Current Culture: en-US diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/currentcalendar1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/currentcalendar1.vb index ca0673723812f..545dd90acdefc 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/currentcalendar1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/currentcalendar1.vb @@ -6,24 +6,24 @@ Imports System.Globalization Imports System.Threading Module Example - Public Sub Main() - ' Change the current culture to zh-TW. - Dim zhTW As CultureInfo = CultureInfo.CreateSpecificCulture("zh-TW") - Thread.CurrentThread.CurrentCulture = zhTW - ' Define a date. - Dim date1 As Date = #1/16/2011# - - ' Display the date using the default (Gregorian) calendar. - Console.WriteLine("Current calendar: {0}", - zhTW.DateTimeFormat.Calendar) - Console.WriteLine(date1.ToString("d")) - - ' Change the current calendar and display the date. - zhTW.DateTimeFormat.Calendar = New TaiwanCalendar() - Console.WriteLine("Current calendar: {0}", - zhTW.DateTimeFormat.Calendar) - Console.WriteLine(date1.ToString("d")) - End Sub + Public Sub Main() + ' Change the current culture to zh-TW. + Dim zhTW As CultureInfo = CultureInfo.CreateSpecificCulture("zh-TW") + Thread.CurrentThread.CurrentCulture = zhTW + ' Define a date. + Dim date1 As Date = #1/16/2011# + + ' Display the date using the default (Gregorian) calendar. + Console.WriteLine("Current calendar: {0}", + zhTW.DateTimeFormat.Calendar) + Console.WriteLine(date1.ToString("d")) + + ' Change the current calendar and display the date. + zhTW.DateTimeFormat.Calendar = New TaiwanCalendar() + Console.WriteLine("Current calendar: {0}", + zhTW.DateTimeFormat.Calendar) + Console.WriteLine(date1.ToString("d")) + End Sub End Module ' The example displays the following output: ' Current calendar: System.Globalization.GregorianCalendar diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/datesandcalendars2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/datesandcalendars2.vb index d1839e7108937..fd529dcbf8d6a 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/datesandcalendars2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/datesandcalendars2.vb @@ -6,49 +6,49 @@ Imports System.Globalization Imports System.Threading Module Example - Public Sub Main() - ' Make Arabic (Egypt) the current culture - ' and Umm al-Qura calendar the current calendar. - Dim arEG As CultureInfo = CultureInfo.CreateSpecificCulture("ar-EG") - Dim cal As Calendar = New UmAlQuraCalendar() - arEG.DateTimeFormat.Calendar = cal - Thread.CurrentThread.CurrentCulture = arEG + Public Sub Main() + ' Make Arabic (Egypt) the current culture + ' and Umm al-Qura calendar the current calendar. + Dim arEG As CultureInfo = CultureInfo.CreateSpecificCulture("ar-EG") + Dim cal As Calendar = New UmAlQuraCalendar() + arEG.DateTimeFormat.Calendar = cal + Thread.CurrentThread.CurrentCulture = arEG - ' Display information on current culture and calendar. - DisplayCurrentInfo() + ' Display information on current culture and calendar. + DisplayCurrentInfo() - ' Instantiate a date object. - Dim date1 As Date = #07/15/2011# + ' Instantiate a date object. + Dim date1 As Date = #07/15/2011# - ' Display the string representation of the date. - Console.WriteLine("Date: {0:d}", date1) - Console.WriteLine("Date in the Invariant Culture: {0}", - date1.ToString("d", CultureInfo.InvariantCulture)) - Console.WriteLine() - - ' Compare DateTime properties and Calendar methods. - Console.WriteLine("DateTime.Month property: {0}", date1.Month) - Console.WriteLine("UmAlQura.GetMonth: {0}", - cal.GetMonth(date1)) - Console.WriteLine() + ' Display the string representation of the date. + Console.WriteLine("Date: {0:d}", date1) + Console.WriteLine("Date in the Invariant Culture: {0}", + date1.ToString("d", CultureInfo.InvariantCulture)) + Console.WriteLine() - Console.WriteLine("DateTime.Day property: {0}", date1.Day) - Console.WriteLine("UmAlQura.GetDayOfMonth: {0}", - cal.GetDayOfMonth(date1)) - Console.WriteLine() - - Console.WriteLine("DateTime.Year property: {0:D4}", date1.Year) - Console.WriteLine("UmAlQura.GetYear: {0}", - cal.GetYear(date1)) - Console.WriteLine() - End Sub - - Private Sub DisplayCurrentInfo() - Console.WriteLine("Current Culture: {0}", - CultureInfo.CurrentCulture.Name) - Console.WriteLine("Current Calendar: {0}", - DateTimeFormatInfo.CurrentInfo.Calendar) - End Sub + ' Compare DateTime properties and Calendar methods. + Console.WriteLine("DateTime.Month property: {0}", date1.Month) + Console.WriteLine("UmAlQura.GetMonth: {0}", + cal.GetMonth(date1)) + Console.WriteLine() + + Console.WriteLine("DateTime.Day property: {0}", date1.Day) + Console.WriteLine("UmAlQura.GetDayOfMonth: {0}", + cal.GetDayOfMonth(date1)) + Console.WriteLine() + + Console.WriteLine("DateTime.Year property: {0:D4}", date1.Year) + Console.WriteLine("UmAlQura.GetYear: {0}", + cal.GetYear(date1)) + Console.WriteLine() + End Sub + + Private Sub DisplayCurrentInfo() + Console.WriteLine("Current Culture: {0}", + CultureInfo.CurrentCulture.Name) + Console.WriteLine("Current Calendar: {0}", + DateTimeFormatInfo.CurrentInfo.Calendar) + End Sub End Module ' The example displays the following output: ' Current Culture: ar-EG diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/formatstrings1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/formatstrings1.vb index a53cac8957eb0..8a4c86d9e10c3 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/formatstrings1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/formatstrings1.vb @@ -7,28 +7,28 @@ Imports System.IO Imports System.Threading Module Example - Public Sub Main() - Dim sw As New StreamWriter(".\eras.txt") - Dim dt As Date = #05/01/2012# - - Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture("ja-JP") - Dim dtfi As DateTimeFormatInfo = culture.DateTimeFormat - dtfi.Calendar = New JapaneseCalendar() - Thread.CurrentThread.CurrentCulture = culture - - sw.WriteLine("{0,-43} {1}", "Full Date and Time Pattern:", dtfi.FullDateTimePattern) - sw.WriteLine(dt.ToString("F")) - sw.WriteLine() - - sw.WriteLine("{0,-43} {1}", "Long Date Pattern:", dtfi.LongDatePattern) - sw.WriteLine(dt.ToString("D")) - sw.WriteLine() - - sw.WriteLine("{0,-43} {1}", "Short Date Pattern:", dtfi.ShortDatePattern) - sw.WriteLine(dt.ToString("d")) - sw.WriteLine() - sw.Close() - End Sub + Public Sub Main() + Dim sw As New StreamWriter(".\eras.txt") + Dim dt As Date = #05/01/2012# + + Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture("ja-JP") + Dim dtfi As DateTimeFormatInfo = culture.DateTimeFormat + dtfi.Calendar = New JapaneseCalendar() + Thread.CurrentThread.CurrentCulture = culture + + sw.WriteLine("{0,-43} {1}", "Full Date and Time Pattern:", dtfi.FullDateTimePattern) + sw.WriteLine(dt.ToString("F")) + sw.WriteLine() + + sw.WriteLine("{0,-43} {1}", "Long Date Pattern:", dtfi.LongDatePattern) + sw.WriteLine(dt.ToString("D")) + sw.WriteLine() + + sw.WriteLine("{0,-43} {1}", "Short Date Pattern:", dtfi.ShortDatePattern) + sw.WriteLine(dt.ToString("d")) + sw.WriteLine() + sw.Close() + End Sub End Module ' The example writes the following output to a file: ' Full Date and Time Pattern: gg y'年'M'月'd'日' H:mm:ss diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/formatstrings2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/formatstrings2.vb index 7dc84edb2ea11..f1a7b6d74e363 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/formatstrings2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/formatstrings2.vb @@ -2,13 +2,13 @@ Option Strict On Module Example - Public Sub Main() - ' - Dim dat As Date = #05/01/2012# - Console.WriteLine("{0:MM-dd-yyyy g}", dat) - ' The example displays the following output: - ' 05-01-2012 A.D. - ' - End Sub + Public Sub Main() + ' + Dim dat As Date = #05/01/2012# + Console.WriteLine("{0:MM-dd-yyyy g}", dat) + ' The example displays the following output: + ' 05-01-2012 A.D. + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/formatstrings3.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/formatstrings3.vb index 2b210c0466d37..567225b0deec7 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/formatstrings3.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/formatstrings3.vb @@ -5,26 +5,26 @@ Option Strict On Imports System.Globalization Module Example - Public Sub Main() - Dim date1 As Date = #8/28/2011# - Dim cal As New JapaneseLunisolarCalendar() - Console.WriteLine("{0} {1:d4}/{2:d2}/{3:d2}", - cal.GetEra(date1), - cal.GetYear(date1), - cal.GetMonth(date1), - cal.GetDayOfMonth(date1)) - - ' Display eras - Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture("ja-JP") - Dim dtfi As DateTimeFormatInfo = culture.DateTimeFormat - dtfi.Calendar = New JapaneseCalendar() - - Console.WriteLine("{0} {1:d4}/{2:d2}/{3:d2}", - dtfi.GetAbbreviatedEraName(cal.GetEra(date1)), - cal.GetYear(date1), - cal.GetMonth(date1), - cal.GetDayOfMonth(date1)) - End Sub + Public Sub Main() + Dim date1 As Date = #8/28/2011# + Dim cal As New JapaneseLunisolarCalendar() + Console.WriteLine("{0} {1:d4}/{2:d2}/{3:d2}", + cal.GetEra(date1), + cal.GetYear(date1), + cal.GetMonth(date1), + cal.GetDayOfMonth(date1)) + + ' Display eras + Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture("ja-JP") + Dim dtfi As DateTimeFormatInfo = culture.DateTimeFormat + dtfi.Calendar = New JapaneseCalendar() + + Console.WriteLine("{0} {1:d4}/{2:d2}/{3:d2}", + dtfi.GetAbbreviatedEraName(cal.GetEra(date1)), + cal.GetYear(date1), + cal.GetMonth(date1), + cal.GetDayOfMonth(date1)) + End Sub End Module ' The example displays the following output: ' 4 0023/07/29 diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/instantiatehcdate1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/instantiatehcdate1.vb index a1daebb64beaa..b5ec5ae5138d8 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/instantiatehcdate1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/instantiatehcdate1.vb @@ -5,26 +5,26 @@ Option Strict On Imports System.Globalization Module Example - Public Sub Main() - Dim hc As New HebrewCalendar() + Public Sub Main() + Dim hc As New HebrewCalendar() - Dim date1 As New Date(5771, 6, 1, hc) - Dim date2 As Date = hc.ToDateTime(5771, 6, 1, 0, 0, 0, 0) - - Console.WriteLine("{0:d} (Gregorian) = {1:d2}/{2:d2}/{3:d4} ({4}): {5}", - date1, - hc.GetMonth(date2), - hc.GetDayOfMonth(date2), - hc.GetYear(date2), - GetCalendarName(hc), - date1.Equals(date2)) - End Sub - - Private Function GetCalendarName(cal As Calendar) As String - Return cal.ToString().Replace("System.Globalization.", ""). - Replace("Calendar", "") - End Function + Dim date1 As New Date(5771, 6, 1, hc) + Dim date2 As Date = hc.ToDateTime(5771, 6, 1, 0, 0, 0, 0) + + Console.WriteLine("{0:d} (Gregorian) = {1:d2}/{2:d2}/{3:d4} ({4}): {5}", + date1, + hc.GetMonth(date2), + hc.GetDayOfMonth(date2), + hc.GetYear(date2), + GetCalendarName(hc), + date1.Equals(date2)) + End Sub + + Private Function GetCalendarName(cal As Calendar) As String + Return cal.ToString().Replace("System.Globalization.", ""). + Replace("Calendar", "") + End Function End Module ' The example displays the following output: ' 2/5/2011 (Gregorian) = 06/01/5771 (Hebrew): True -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/instantiatewithera1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/instantiatewithera1.vb index 4c3325a21de6e..79b9f6bf71d39 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/instantiatewithera1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/instantiatewithera1.vb @@ -1,26 +1,26 @@ Imports System.Globalization Module Example - Public Sub Main() - Dim year As Integer = 2 - Dim month As Integer = 1 - Dim day As Integer = 1 - Dim cal As New JapaneseCalendar() + Public Sub Main() + Dim year As Integer = 2 + Dim month As Integer = 1 + Dim day As Integer = 1 + Dim cal As New JapaneseCalendar() - Console.WriteLine("Date instantiated without an era:") - Dim date1 As New Date(year, month, day, 0, 0, 0, 0, cal) - Console.WriteLine("{0}/{1}/{2} in Japanese Calendar -> {3:d} in Gregorian", - cal.GetMonth(date1), cal.GetDayOfMonth(date1), - cal.GetYear(date1), date1) - Console.WriteLine() - - Console.WriteLine("Dates instantiated with eras:") - For Each era As Integer In cal.Eras - Dim date2 As Date = cal.ToDateTime(year, month, day, 0, 0, 0, 0, era) - Console.WriteLine("{0}/{1}/{2} era {3} in Japanese Calendar -> {4:d} in Gregorian", - cal.GetMonth(date2), cal.GetDayOfMonth(date2), - cal.GetYear(date2), cal.GetEra(date2), date2) - Next - End Sub + Console.WriteLine("Date instantiated without an era:") + Dim date1 As New Date(year, month, day, 0, 0, 0, 0, cal) + Console.WriteLine("{0}/{1}/{2} in Japanese Calendar -> {3:d} in Gregorian", + cal.GetMonth(date1), cal.GetDayOfMonth(date1), + cal.GetYear(date1), date1) + Console.WriteLine() + + Console.WriteLine("Dates instantiated with eras:") + For Each era As Integer In cal.Eras + Dim date2 As Date = cal.ToDateTime(year, month, day, 0, 0, 0, 0, era) + Console.WriteLine("{0}/{1}/{2} era {3} in Japanese Calendar -> {4:d} in Gregorian", + cal.GetMonth(date2), cal.GetDayOfMonth(date2), + cal.GetYear(date2), cal.GetEra(date2), date2) + Next + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/minsupporteddatetime1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/minsupporteddatetime1.vb index 585f2c2339966..a26c1fe8e58b5 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/minsupporteddatetime1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/minsupporteddatetime1.vb @@ -6,42 +6,42 @@ Imports System.Globalization Imports System.Threading Module Example - Public Sub Main() - Dim dat As Date = DateTime.MinValue - - ' Change the current culture to ja-JP with the Japanese Calendar. - Dim jaJP As CultureInfo = CultureInfo.CreateSpecificCulture("ja-JP") - jaJP.DateTimeFormat.Calendar = New JapaneseCalendar() - Thread.CurrentThread.CurrentCulture = jaJP - Console.WriteLine("Earliest supported date by {1} calendar: {0:d}", - jaJP.DateTimeFormat.Calendar.MinSupportedDateTime, - GetCalendarName(jaJP)) - ' Attempt to display the date. - Console.WriteLine(dat.ToString()) - Console.WriteLine() - - ' Change the current culture to ar-EG with the Um Al Qura calendar. - Dim arEG As CultureInfo = CultureInfo.CreateSpecificCulture("ar-EG") - arEG.DateTimeFormat.Calendar = New UmAlQuraCalendar() - Thread.CurrentThread.CurrentCulture = arEG - Console.WriteLine("Earliest supported date by {1} calendar: {0:d}", - arEG.DateTimeFormat.Calendar.MinSupportedDateTime, - GetCalendarName(arEG)) - ' Attempt to display the date. - Console.WRiteLine(dat.ToString()) - Console.WRiteLine() - - ' Change the current culture to en-US. - Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US") - Console.WriteLine(dat.ToString(jaJP)) - Console.WriteLine(dat.ToString(arEG)) - Console.WriteLine(dat.ToString("d")) - End Sub - - Private Function GetCalendarName(culture As CultureInfo) As String - Dim cal As Calendar = culture.DateTimeFormat.Calendar - Return cal.GetType().Name.Replace("System.Globalization.", "").Replace("Calendar", "") - End Function + Public Sub Main() + Dim dat As Date = DateTime.MinValue + + ' Change the current culture to ja-JP with the Japanese Calendar. + Dim jaJP As CultureInfo = CultureInfo.CreateSpecificCulture("ja-JP") + jaJP.DateTimeFormat.Calendar = New JapaneseCalendar() + Thread.CurrentThread.CurrentCulture = jaJP + Console.WriteLine("Earliest supported date by {1} calendar: {0:d}", + jaJP.DateTimeFormat.Calendar.MinSupportedDateTime, + GetCalendarName(jaJP)) + ' Attempt to display the date. + Console.WriteLine(dat.ToString()) + Console.WriteLine() + + ' Change the current culture to ar-EG with the Um Al Qura calendar. + Dim arEG As CultureInfo = CultureInfo.CreateSpecificCulture("ar-EG") + arEG.DateTimeFormat.Calendar = New UmAlQuraCalendar() + Thread.CurrentThread.CurrentCulture = arEG + Console.WriteLine("Earliest supported date by {1} calendar: {0:d}", + arEG.DateTimeFormat.Calendar.MinSupportedDateTime, + GetCalendarName(arEG)) + ' Attempt to display the date. + Console.WRiteLine(dat.ToString()) + Console.WRiteLine() + + ' Change the current culture to en-US. + Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US") + Console.WriteLine(dat.ToString(jaJP)) + Console.WriteLine(dat.ToString(arEG)) + Console.WriteLine(dat.ToString("d")) + End Sub + + Private Function GetCalendarName(culture As CultureInfo) As String + Dim cal As Calendar = culture.DateTimeFormat.Calendar + Return cal.GetType().Name.Replace("System.Globalization.", "").Replace("Calendar", "") + End Function End Module ' The example displays the following output: ' Earliest supported date by Japanese calendar: 明治 1/9/8 diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/noncurrentcalendar1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/noncurrentcalendar1.vb index 78696860e198a..7a3c34a890167 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/noncurrentcalendar1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.calendars/vb/noncurrentcalendar1.vb @@ -5,18 +5,18 @@ Option Strict On Imports System.Globalization Module Example - Public Sub Main() - Dim julian As New JulianCalendar() - Dim date1 As New Date(1905, 1, 9, julian) - - Console.WriteLine("Date ({0}): {1:d}", - CultureInfo.CurrentCulture.Calendar, - date1) - Console.WriteLine("Date in Julian calendar: {0:d2}/{1:d2}/{2:d4}", - julian.GetMonth(date1), - julian.GetDayOfMonth(date1), - julian.GetYear(date1)) - End Sub + Public Sub Main() + Dim julian As New JulianCalendar() + Dim date1 As New Date(1905, 1, 9, julian) + + Console.WriteLine("Date ({0}): {1:d}", + CultureInfo.CurrentCulture.Calendar, + date1) + Console.WriteLine("Date in Julian calendar: {0:d2}/{1:d2}/{2:d4}", + julian.GetMonth(date1), + julian.GetDayOfMonth(date1), + julian.GetYear(date1)) + End Sub End Module ' The example displays the following output: ' Date (System.Globalization.GregorianCalendar): 1/22/1905 diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.cancellation.callback/vb/howtoexample1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.cancellation.callback/vb/howtoexample1.vb index 4c408ef0ad8de..1f7f8633d733e 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.cancellation.callback/vb/howtoexample1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.cancellation.callback/vb/howtoexample1.vb @@ -9,27 +9,27 @@ Class CancelWithCallback Shared Sub Main() Dim cts As New CancellationTokenSource() Dim token As CancellationToken = cts.Token - + ' Start cancelable task. Dim t As Task = Task.Run( Sub() - Dim wc As New WebClient() - - ' Create an event handler to receive the result. - AddHandler wc.DownloadStringCompleted, - Sub(obj, e) - ' Check status of WebClient, not external token. - If Not e.Cancelled Then - Console.WriteLine("The download has completed:" + vbCrLf) - Console.WriteLine(e.Result + vbCrLf + vbCrLf + "Press any key.") - Else - Console.WriteLine("Download was canceled.") - End If + Dim wc As New WebClient() + + ' Create an event handler to receive the result. + AddHandler wc.DownloadStringCompleted, + Sub(obj, e) + ' Check status of WebClient, not external token. + If Not e.Cancelled Then + Console.WriteLine("The download has completed:" + vbCrLf) + Console.WriteLine(e.Result + vbCrLf + vbCrLf + "Press any key.") + Else + Console.WriteLine("Download was canceled.") + End If End Sub - Using ctr As CancellationTokenRegistration = token.Register(Sub() wc.CancelAsync()) - Console.WriteLine("Starting request..." + vbCrLf) - wc.DownloadStringAsync(New Uri("http://www.contoso.com")) - End Using + Using ctr As CancellationTokenRegistration = token.Register(Sub() wc.CancelAsync()) + Console.WriteLine("Starting request..." + vbCrLf) + wc.DownloadStringAsync(New Uri("http://www.contoso.com")) + End Using End Sub, token) Console.WriteLine("Press 'c' to cancel." + vbCrLf) diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.choosingdates/vb/datetimereplacement1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.choosingdates/vb/datetimereplacement1.vb index 78c7e2096b679..f7b529a46e15f 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.choosingdates/vb/datetimereplacement1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.choosingdates/vb/datetimereplacement1.vb @@ -14,7 +14,7 @@ Public Structure StoreInfo Public Function IsOpenNow() As Boolean Return IsOpenAt(Date.Now.TimeOfDay) End Function - + Public Function IsOpenAt(time As TimeSpan) As Boolean Dim local As TimeZoneInfo = TimeZoneInfo.Local Dim offset As TimeSpan = TimeZoneInfo.Local.BaseUtcOffset @@ -42,27 +42,27 @@ End Structure ' Module Example - Public Sub Main() - ' Instantiate a StoreInfo object. - Dim store103 As New StoreInfo() - store103.store = "Store #103" - store103.tz = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time") - ' Store opens at 8:00. - store103.open = new TimeSpan(8, 0, 0) - ' Store closes at 9:30. - store103.close = new TimeSpan(21, 30, 0) - - Console.WriteLine("Store is open now at {0}: {1}", - Date.Now.TimeOfDay, store103.IsOpenNow()) - Dim times() As TimeSpan = { New TimeSpan(8, 0, 0), - New TimeSpan(21, 0, 0), - New TimeSpan(4, 59, 0), - New TimeSpan(18, 31, 0) } - For Each time In times - Console.WriteLine("Store is open at {0}: {1}", - time, store103.IsOpenAt(time)) - Next - End Sub + Public Sub Main() + ' Instantiate a StoreInfo object. + Dim store103 As New StoreInfo() + store103.store = "Store #103" + store103.tz = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time") + ' Store opens at 8:00. + store103.open = new TimeSpan(8, 0, 0) + ' Store closes at 9:30. + store103.close = new TimeSpan(21, 30, 0) + + Console.WriteLine("Store is open now at {0}: {1}", + Date.Now.TimeOfDay, store103.IsOpenNow()) + Dim times() As TimeSpan = {New TimeSpan(8, 0, 0), + New TimeSpan(21, 0, 0), + New TimeSpan(4, 59, 0), + New TimeSpan(18, 31, 0)} + For Each time In times + Console.WriteLine("Store is open at {0}: {1}", + time, store103.IsOpenAt(time)) + Next + End Sub End Module ' The example displays the following output: ' Store is open now at 15:29:01.6129911: True diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/accessibility1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/accessibility1.vb index aef1722ea7abd..61195d08499a1 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/accessibility1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/accessibility1.vb @@ -5,54 +5,54 @@ Option Strict On Public Class Animal - Private _species As String - - Public Sub New(species As String) - _species = species - End Sub - - Public Overridable ReadOnly Property Species As String - Get - Return _species - End Get - End Property - - Public Overrides Function ToString() As String - Return _species - End Function + Private _species As String + + Public Sub New(species As String) + _species = species + End Sub + + Public Overridable ReadOnly Property Species As String + Get + Return _species + End Get + End Property + + Public Overrides Function ToString() As String + Return _species + End Function End Class Public Class Human : Inherits Animal - Private _name As String - - Public Sub New(name As String) - MyBase.New("Homo Sapiens") - _name = name - End Sub - - Public ReadOnly Property Name As String - Get - Return _name - End Get - End Property - - Private Overrides ReadOnly Property Species As String - Get - Return MyBase.Species - End Get - End Property - - Public Overrides Function ToString() As String - Return _name - End Function + Private _name As String + + Public Sub New(name As String) + MyBase.New("Homo Sapiens") + _name = name + End Sub + + Public ReadOnly Property Name As String + Get + Return _name + End Get + End Property + + Private Overrides ReadOnly Property Species As String + Get + Return MyBase.Species + End Get + End Property + + Public Overrides Function ToString() As String + Return _name + End Function End Class Public Module Example - Public Sub Main() - Dim p As New Human("John") - Console.WriteLine(p.Species) - Console.WriteLine(p.ToString()) - End Sub + Public Sub Main() + Dim p As New Human("John") + Console.WriteLine(p.Species) + Console.WriteLine(p.ToString()) + End Sub End Module ' The example displays the following output: ' 'Private Overrides ReadOnly Property Species As String' cannot override diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/accessibility3.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/accessibility3.vb index ee1a47816634a..42c823d21cd9f 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/accessibility3.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/accessibility3.vb @@ -4,29 +4,29 @@ Option Strict On ' Imports System.Text - + Public Class StringWrapper - - Dim internalString As String - Dim internalSB As StringBuilder = Nothing - Dim useSB As Boolean = False - - Public Sub New(type As StringOperationType) - If type = StringOperationType.Normal Then - useSB = False - Else - internalSB = New StringBuilder() - useSB = True - End If - End Sub - - ' The remaining source code... + + Dim internalString As String + Dim internalSB As StringBuilder = Nothing + Dim useSB As Boolean = False + + Public Sub New(type As StringOperationType) + If type = StringOperationType.Normal Then + useSB = False + Else + internalSB = New StringBuilder() + useSB = True + End If + End Sub + + ' The remaining source code... End Class Friend Enum StringOperationType As Integer - Normal = 0 - Dynamic = 1 + Normal = 0 + Dynamic = 1 End Enum ' The attempt to compile the example displays the following output: ' error BC30909: 'type' cannot expose type 'StringOperationType' @@ -37,9 +37,8 @@ End Enum ' Module Example - Public Sub Main() - - End Sub + Public Sub Main() + + End Sub End Module - \ No newline at end of file diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/array1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/array1.vb index 5acbdffcdf660..f7dc71ccbf537 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/array1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/array1.vb @@ -8,29 +8,29 @@ Option Strict On Public Class Numbers - Public Shared Function GetTenPrimes() As Array - Dim arr As Array = Array.CreateInstance(GetType(Int32), {10}, {1}) - arr.SetValue(1, 1) - arr.SetValue(2, 2) - arr.SetValue(3, 3) - arr.SetValue(5, 4) - arr.SetValue(7, 5) - arr.SetValue(11, 6) - arr.SetValue(13, 7) - arr.SetValue(17, 8) - arr.SetValue(19, 9) - arr.SetValue(23, 10) - - Return arr - End Function + Public Shared Function GetTenPrimes() As Array + Dim arr As Array = Array.CreateInstance(GetType(Int32), {10}, {1}) + arr.SetValue(1, 1) + arr.SetValue(2, 2) + arr.SetValue(3, 3) + arr.SetValue(5, 4) + arr.SetValue(7, 5) + arr.SetValue(11, 6) + arr.SetValue(13, 7) + arr.SetValue(17, 8) + arr.SetValue(19, 9) + arr.SetValue(23, 10) + + Return arr + End Function End Class ' Module Example - Public Sub Main() - For Each number In Numbers.GetTenPrimes() - Console.WriteLine(number) - Next - End Sub + Public Sub Main() + For Each number In Numbers.GetTenPrimes() + Console.WriteLine(number) + Next + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/array2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/array2.vb index 8a0f682241289..57655cc21339a 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/array2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/array2.vb @@ -5,14 +5,14 @@ Option Strict On Public Class Numbers - Public Shared Function GetTenPrimes() As UInt32() - Return { 1ui, 2ui, 3ui, 5ui, 7ui, 11ui, 13ui, 17ui, 19ui } - End Function - - Public Shared Function GetFivePrimes() As Object() - Dim arr() As Object = { 1, 2, 3, 5ui, 7ui } - Return arr - End Function + Public Shared Function GetTenPrimes() As UInt32() + Return {1ui, 2ui, 3ui, 5ui, 7ui, 11ui, 13ui, 17ui, 19ui} + End Function + + Public Shared Function GetFivePrimes() As Object() + Dim arr() As Object = {1, 2, 3, 5ui, 7ui} + Return arr + End Function End Class ' Compilation produces a compiler warning like the following: ' warning BC40027: Return type of function 'GetTenPrimes' is not CLS-compliant. @@ -22,10 +22,10 @@ End Class ' Module Example - Public Sub Main() - For Each obj In Numbers.GetFivePrimes() - Console.WriteLine("{0} ({1})", obj, obj.GetType().Name) - Next - End Sub + Public Sub Main() + For Each obj In Numbers.GetFivePrimes() + Console.WriteLine("{0} ({1})", obj, obj.GetType().Name) + Next + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/array3.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/array3.vb index a50c12deac9fa..acbee58b8cf9b 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/array3.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/array3.vb @@ -7,44 +7,44 @@ Imports System.Numerics Public Module Numbers - Public Function GetSquares(numbers As Byte()) As Byte() - Dim numbersOut(numbers.Length - 1) As Byte - For ctr As Integer = 0 To numbers.Length - 1 - Dim square As Integer = (CInt(numbers(ctr)) * CInt(numbers(ctr))) - If square <= Byte.MaxValue Then - numbersOut(ctr) = CByte(square) - ' If there's an overflow, assign MaxValue to the corresponding - ' element. - Else - numbersOut(ctr) = Byte.MaxValue - End If - Next - Return numbersOut - End Function + Public Function GetSquares(numbers As Byte()) As Byte() + Dim numbersOut(numbers.Length - 1) As Byte + For ctr As Integer = 0 To numbers.Length - 1 + Dim square As Integer = (CInt(numbers(ctr)) * CInt(numbers(ctr))) + If square <= Byte.MaxValue Then + numbersOut(ctr) = CByte(square) + ' If there's an overflow, assign MaxValue to the corresponding + ' element. + Else + numbersOut(ctr) = Byte.MaxValue + End If + Next + Return numbersOut + End Function - Public Function GetSquares(numbers As BigInteger()) As BigInteger() - Dim numbersOut(numbers.Length - 1) As BigInteger - For ctr As Integer = 0 To numbers.Length - 1 - numbersOut(ctr) = numbers(ctr) * numbers(ctr) - Next - Return numbersOut - End Function + Public Function GetSquares(numbers As BigInteger()) As BigInteger() + Dim numbersOut(numbers.Length - 1) As BigInteger + For ctr As Integer = 0 To numbers.Length - 1 + numbersOut(ctr) = numbers(ctr) * numbers(ctr) + Next + Return numbersOut + End Function End Module ' Module Example - Public Sub Main() - Dim bytes() As Byte = Numbers.GetSquares( { CByte(3), CByte(10), - CByte(13), CByte(20) } ) - For Each byt In bytes - Console.Write("{0} ", byt) - Next - Console.WriteLine() - Dim bigs() As BigInteger = { 1034, 1058, 100, 12399 } - For Each bigSquare In Numbers.GetSquares(bigs) - Console.Write("{0:N0} ", bigSquare) - Next - Console.WriteLine() - End Sub + Public Sub Main() + Dim bytes() As Byte = Numbers.GetSquares({CByte(3), CByte(10), + CByte(13), CByte(20)}) + For Each byt In bytes + Console.Write("{0} ", byt) + Next + Console.WriteLine() + Dim bigs() As BigInteger = {1034, 1058, 100, 12399} + For Each bigSquare In Numbers.GetSquares(bigs) + Console.Write("{0:N0} ", bigSquare) + Next + Console.WriteLine() + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/attribute1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/attribute1.vb index 63b5d82211bc3..a17088bc20ed4 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/attribute1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/attribute1.vb @@ -6,21 +6,21 @@ Option Strict On _ Public Class NumericAttribute - Private _isNumeric As Boolean - - Public Sub New(isNumeric As Boolean) - _isNumeric = isNumeric - End Sub - - Public ReadOnly Property IsNumeric As Boolean - Get - Return _isNumeric - End Get - End Property + Private _isNumeric As Boolean + + Public Sub New(isNumeric As Boolean) + _isNumeric = isNumeric + End Sub + + Public ReadOnly Property IsNumeric As Boolean + Get + Return _isNumeric + End Get + End Property End Class Public Structure UDouble - Dim Value As Double + Dim Value As Double End Structure ' Compilation produces a compiler error like the following: ' error BC31504: 'NumericAttribute' cannot be used as an attribute because it @@ -31,8 +31,8 @@ End Structure ' Module Example - Public Sub Main() - - End Sub + Public Sub Main() + + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/attribute2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/attribute2.vb index fe80ec9e469e6..60da529421f2f 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/attribute2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/attribute2.vb @@ -2,37 +2,37 @@ Option Strict On ' - + Public Enum DescriptorType As Integer - Type = 0 - Member = 1 + Type = 0 + Member = 1 End Enum Public Class Descriptor - Public Type As DescriptorType - Public Description As String + Public Type As DescriptorType + Public Description As String End Class _ Public Class DescriptionAttribute : Inherits Attribute - Private desc As Descriptor - - Public Sub New(d As Descriptor) - desc = d - End Sub - - Public ReadOnly Property Descriptor As Descriptor - Get - Return desc - End Get - End Property + Private desc As Descriptor + + Public Sub New(d As Descriptor) + desc = d + End Sub + + Public ReadOnly Property Descriptor As Descriptor + Get + Return desc + End Get + End Property End Class ' Module Example - Public Sub Main() + Public Sub Main() - End Sub + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/convert1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/convert1.vb index b8f767c077ca4..35d14c3ce23b0 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/convert1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/convert1.vb @@ -3,71 +3,71 @@ Option Strict On ' Public Structure UDouble - Private number As Double - - Public Sub New(value As Double) - If value < 0 Then - Throw New InvalidCastException("A negative value cannot be converted to a UDouble.") - End If - number = value - End Sub - - Public Sub New(value As Single) - If value < 0 Then - Throw New InvalidCastException("A negative value cannot be converted to a UDouble.") - End If - number = value - End Sub - - Public Shared ReadOnly MinValue As UDouble = CType(0.0, UDouble) - Public Shared ReadOnly MaxValue As UDouble = Double.MaxValue - - Public Shared Widening Operator CType(value As UDouble) As Double - Return value.number - End Operator - - Public Shared Narrowing Operator CType(value As UDouble) As Single - If value.number > CDbl(Single.MaxValue) Then - Throw New InvalidCastException("A UDouble value is out of range of the Single type.") - End If - Return CSng(value.number) - End Operator - - Public Shared Narrowing Operator CType(value As Double) As UDouble - If value < 0 Then - Throw New InvalidCastException("A negative value cannot be converted to a UDouble.") - End If - Return New UDouble(value) - End Operator + Private number As Double - Public Shared Narrowing Operator CType(value As Single) As UDouble - If value < 0 Then - Throw New InvalidCastException("A negative value cannot be converted to a UDouble.") - End If - Return New UDouble(value) - End Operator + Public Sub New(value As Double) + If value < 0 Then + Throw New InvalidCastException("A negative value cannot be converted to a UDouble.") + End If + number = value + End Sub - Public Shared Function ToDouble(value As UDouble) As Double - Return CType(value, Double) - End Function + Public Sub New(value As Single) + If value < 0 Then + Throw New InvalidCastException("A negative value cannot be converted to a UDouble.") + End If + number = value + End Sub - Public Shared Function ToSingle(value As UDouble) As Single - Return CType(value, Single) - End Function + Public Shared ReadOnly MinValue As UDouble = CType(0.0, UDouble) + Public Shared ReadOnly MaxValue As UDouble = Double.MaxValue - Public Shared Function FromDouble(value As Double) As UDouble - Return New UDouble(value) - End Function - - Public Shared Function FromSingle(value As Single) As UDouble - Return New UDouble(value) - End Function + Public Shared Widening Operator CType(value As UDouble) As Double + Return value.number + End Operator + + Public Shared Narrowing Operator CType(value As UDouble) As Single + If value.number > CDbl(Single.MaxValue) Then + Throw New InvalidCastException("A UDouble value is out of range of the Single type.") + End If + Return CSng(value.number) + End Operator + + Public Shared Narrowing Operator CType(value As Double) As UDouble + If value < 0 Then + Throw New InvalidCastException("A negative value cannot be converted to a UDouble.") + End If + Return New UDouble(value) + End Operator + + Public Shared Narrowing Operator CType(value As Single) As UDouble + If value < 0 Then + Throw New InvalidCastException("A negative value cannot be converted to a UDouble.") + End If + Return New UDouble(value) + End Operator + + Public Shared Function ToDouble(value As UDouble) As Double + Return CType(value, Double) + End Function + + Public Shared Function ToSingle(value As UDouble) As Single + Return CType(value, Single) + End Function + + Public Shared Function FromDouble(value As Double) As UDouble + Return New UDouble(value) + End Function + + Public Shared Function FromSingle(value As Single) As UDouble + Return New UDouble(value) + End Function End Structure ' Module Example - Public Sub Main() + Public Sub Main() - End Sub + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/ctor1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/ctor1.vb index d5367d4f6d3da..345334edb33dd 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/ctor1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/ctor1.vb @@ -2,53 +2,53 @@ Option Strict On ' - + Public Class Person - Private fName, lName, _id As String - - Public Sub New(firstName As String, lastName As String, id As String) - If String.IsNullOrEmpty(firstName + lastName) Then - Throw New ArgumentNullException("Either a first name or a last name must be provided.") - End If - - fName = firstName - lName = lastName - _id = id - End Sub - - Public ReadOnly Property FirstName As String - Get - Return fName - End Get - End Property + Private fName, lName, _id As String - Public ReadOnly Property LastName As String - Get - Return lName - End Get - End Property - - Public ReadOnly Property Id As String - Get - Return _id - End Get - End Property + Public Sub New(firstName As String, lastName As String, id As String) + If String.IsNullOrEmpty(firstName + lastName) Then + Throw New ArgumentNullException("Either a first name or a last name must be provided.") + End If - Public Overrides Function ToString() As String - Return String.Format("{0}{1}{2}", fName, - If(String.IsNullOrEmpty(fName), "", " "), - lName) - End Function + fName = firstName + lName = lastName + _id = id + End Sub + + Public ReadOnly Property FirstName As String + Get + Return fName + End Get + End Property + + Public ReadOnly Property LastName As String + Get + Return lName + End Get + End Property + + Public ReadOnly Property Id As String + Get + Return _id + End Get + End Property + + Public Overrides Function ToString() As String + Return String.Format("{0}{1}{2}", fName, + If(String.IsNullOrEmpty(fName), "", " "), + lName) + End Function End Class Public Class Doctor : Inherits Person - Public Sub New(firstName As String, lastName As String, id As String) - End Sub + Public Sub New(firstName As String, lastName As String, id As String) + End Sub - Public Overrides Function ToString() As String - Return "Dr. " + MyBase.ToString() - End Function + Public Overrides Function ToString() As String + Return "Dr. " + MyBase.ToString() + End Function End Class ' Attempting to compile the example displays output like the following: ' Ctor1.vb(46) : error BC30148: First statement of this 'Sub New' must be a call @@ -60,8 +60,8 @@ End Class ' Module Example - Public Sub Main() + Public Sub Main() - End Sub + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/eii1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/eii1.vb index 8164680398693..fd5e349f2627c 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/eii1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/eii1.vb @@ -5,40 +5,40 @@ Option Strict On Public Interface IFahrenheit - Function GetTemperature() As Decimal + Function GetTemperature() As Decimal End Interface - + Public Interface ICelsius - Function GetTemperature() As Decimal + Function GetTemperature() As Decimal End Interface Public Class Temperature : Implements ICelsius, IFahrenheit - Private _value As Decimal - - Public Sub New(value As Decimal) - ' We assume that this is the Celsius value. - _value = value - End Sub - - Public Function GetFahrenheit() As Decimal _ - Implements IFahrenheit.GetTemperature - Return _value * 9 / 5 + 32 - End Function - - Public Function GetCelsius() As Decimal _ - Implements ICelsius.GetTemperature - Return _value - End Function + Private _value As Decimal + + Public Sub New(value As Decimal) + ' We assume that this is the Celsius value. + _value = value + End Sub + + Public Function GetFahrenheit() As Decimal _ + Implements IFahrenheit.GetTemperature + Return _value * 9 / 5 + 32 + End Function + + Public Function GetCelsius() As Decimal _ + Implements ICelsius.GetTemperature + Return _value + End Function End Class Module Example - Public Sub Main() - Dim temp As New Temperature(100.0d) - Console.WriteLine("Temperature in Celsius: {0} degrees", - temp.GetCelsius()) - Console.WriteLine("Temperature in Fahrenheit: {0} degrees", - temp.GetFahrenheit()) - End Sub + Public Sub Main() + Dim temp As New Temperature(100.0d) + Console.WriteLine("Temperature in Celsius: {0} degrees", + temp.GetCelsius()) + Console.WriteLine("Temperature in Fahrenheit: {0} degrees", + temp.GetFahrenheit()) + End Sub End Module ' The example displays the following output: ' Temperature in Celsius: 100.0 degrees diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/enum3.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/enum3.vb index 5b87bf84a756a..986c6a6254b70 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/enum3.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/enum3.vb @@ -5,18 +5,18 @@ Option Strict On Public Enum Size As UInt32 - Unspecified = 0 - XSmall = 1 - Small = 2 - Medium = 3 - Large = 4 - XLarge = 5 + Unspecified = 0 + XSmall = 1 + Small = 2 + Medium = 3 + Large = 4 + XLarge = 5 End Enum Public Class Clothing - Public Name As String - Public Type As String - Public Size As Size + Public Name As String + Public Type As String + Public Size As Size End Class ' The attempt to compile the example displays a compiler warning like the following: ' Enum3.vb(6) : warning BC40032: Underlying type 'UInt32' of Enum is not CLS-compliant. @@ -24,6 +24,6 @@ End Class ' Public Enum Size As UInt32 ' ~~~~ ' - + diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/event1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/event1.vb index 661bba592068c..35a0450150665 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/event1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/event1.vb @@ -7,124 +7,124 @@ Imports System.Collections.Generic -Public Class TemperatureChangedEventArgs : Inherits EventArgs - Private originalTemp As Decimal - Private newTemp As Decimal - Private [when] As DateTimeOffset - - Public Sub New(original As Decimal, [new] As Decimal, [time] As DateTimeOffset) - originalTemp = original - newTemp = [new] - [when] = [time] - End Sub - - Public ReadOnly Property OldTemperature As Decimal - Get - Return originalTemp - End Get - End Property - - Public ReadOnly Property CurrentTemperature As Decimal - Get - Return newTemp - End Get - End Property - - Public ReadOnly Property [Time] As DateTimeOffset - Get - Return [when] - End Get - End Property +Public Class TemperatureChangedEventArgs : Inherits EventArgs + Private originalTemp As Decimal + Private newTemp As Decimal + Private [when] As DateTimeOffset + + Public Sub New(original As Decimal, [new] As Decimal, [time] As DateTimeOffset) + originalTemp = original + newTemp = [new] + [when] = [time] + End Sub + + Public ReadOnly Property OldTemperature As Decimal + Get + Return originalTemp + End Get + End Property + + Public ReadOnly Property CurrentTemperature As Decimal + Get + Return newTemp + End Get + End Property + + Public ReadOnly Property [Time] As DateTimeOffset + Get + Return [when] + End Get + End Property End Class Public Delegate Sub TemperatureChanged(sender As Object, e As TemperatureChangedEventArgs) Public Class Temperature - Private Structure TemperatureInfo - Dim Temperature As Decimal - Dim Recorded As DateTimeOffset - End Structure - - Public Event TemperatureChanged As TemperatureChanged - - Private previous As Decimal - Private current As Decimal - Private tolerance As Decimal - Private tis As New List(Of TemperatureInfo) - - Public Sub New(temperature As Decimal, tolerance As Decimal) - current = temperature - Dim ti As New TemperatureInfo() - ti.Temperature = temperature - ti.Recorded = DateTimeOffset.UtcNow - tis.Add(ti) - Me.tolerance = tolerance - End Sub - - Public Property CurrentTemperature As Decimal - Get - Return current - End Get - Set - Dim ti As New TemperatureInfo - ti.Temperature = value - ti.Recorded = DateTimeOffset.UtcNow - previous = current - current = value - If Math.Abs(current - previous) >= tolerance Then - raise_TemperatureChanged(New TemperatureChangedEventArgs(previous, current, ti.Recorded)) - End If - End Set - End Property - - Public Sub raise_TemperatureChanged(eventArgs As TemperatureChangedEventArgs) - If TemperatureChangedEvent Is Nothing Then Exit Sub - - Dim ListenerList() As System.Delegate = TemperatureChangedEvent.GetInvocationList() - For Each d As TemperatureChanged In TemperatureChangedEvent.GetInvocationList() - If d.Method.Name.Contains("Duplicate") Then - Console.WriteLine("Duplicate event handler; event handler not executed.") - Else - d.Invoke(Me, eventArgs) - End If - Next - End Sub + Private Structure TemperatureInfo + Dim Temperature As Decimal + Dim Recorded As DateTimeOffset + End Structure + + Public Event TemperatureChanged As TemperatureChanged + + Private previous As Decimal + Private current As Decimal + Private tolerance As Decimal + Private tis As New List(Of TemperatureInfo) + + Public Sub New(temperature As Decimal, tolerance As Decimal) + current = temperature + Dim ti As New TemperatureInfo() + ti.Temperature = temperature + ti.Recorded = DateTimeOffset.UtcNow + tis.Add(ti) + Me.tolerance = tolerance + End Sub + + Public Property CurrentTemperature As Decimal + Get + Return current + End Get + Set + Dim ti As New TemperatureInfo + ti.Temperature = value + ti.Recorded = DateTimeOffset.UtcNow + previous = current + current = value + If Math.Abs(current - previous) >= tolerance Then + raise_TemperatureChanged(New TemperatureChangedEventArgs(previous, current, ti.Recorded)) + End If + End Set + End Property + + Public Sub raise_TemperatureChanged(eventArgs As TemperatureChangedEventArgs) + If TemperatureChangedEvent Is Nothing Then Exit Sub + + Dim ListenerList() As System.Delegate = TemperatureChangedEvent.GetInvocationList() + For Each d As TemperatureChanged In TemperatureChangedEvent.GetInvocationList() + If d.Method.Name.Contains("Duplicate") Then + Console.WriteLine("Duplicate event handler; event handler not executed.") + Else + d.Invoke(Me, eventArgs) + End If + Next + End Sub End Class Public Class Example - Public WithEvents temp As Temperature - - Public Shared Sub Main() - Dim ex As New Example() - End Sub - - Public Sub New() - temp = New Temperature(65, 3) - RecordTemperatures() - Dim ex As New Example(temp) - ex.RecordTemperatures() - End Sub - - Public Sub New(t As Temperature) - temp = t - RecordTemperatures() - End Sub - - Public Sub RecordTemperatures() - temp.CurrentTemperature = 66 - temp.CurrentTemperature = 63 - - End Sub - - Friend Shared Sub TemperatureNotification(sender As Object, e As TemperatureChangedEventArgs) _ - Handles temp.TemperatureChanged - Console.WriteLine("Notification 1: The temperature changed from {0} to {1}", e.OldTemperature, e.CurrentTemperature) - End Sub - - Friend Shared Sub DuplicateTemperatureNotification(sender As Object, e As TemperatureChangedEventArgs) _ - Handles temp.TemperatureChanged - Console.WriteLine("Notification 2: The temperature changed from {0} to {1}", e.OldTemperature, e.CurrentTemperature) - End Sub + Public WithEvents temp As Temperature + + Public Shared Sub Main() + Dim ex As New Example() + End Sub + + Public Sub New() + temp = New Temperature(65, 3) + RecordTemperatures() + Dim ex As New Example(temp) + ex.RecordTemperatures() + End Sub + + Public Sub New(t As Temperature) + temp = t + RecordTemperatures() + End Sub + + Public Sub RecordTemperatures() + temp.CurrentTemperature = 66 + temp.CurrentTemperature = 63 + + End Sub + + Friend Shared Sub TemperatureNotification(sender As Object, e As TemperatureChangedEventArgs) _ + Handles temp.TemperatureChanged + Console.WriteLine("Notification 1: The temperature changed from {0} to {1}", e.OldTemperature, e.CurrentTemperature) + End Sub + + Friend Shared Sub DuplicateTemperatureNotification(sender As Object, e As TemperatureChangedEventArgs) _ + Handles temp.TemperatureChanged + Console.WriteLine("Notification 2: The temperature changed from {0} to {1}", e.OldTemperature, e.CurrentTemperature) + End Sub End Class ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/exceptions1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/exceptions1.vb index dc9111e9e325c..a6849aa4fc93c 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/exceptions1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/exceptions1.vb @@ -5,31 +5,31 @@ Option Strict On Imports System.Runtime.CompilerServices - -Public Class ErrorClass - Dim msg As String - - Public Sub New(errorMessage As String) - msg = errorMessage - End Sub - - Public ReadOnly Property Message As String - Get - Return msg - End Get - End Property + +Public Class ErrorClass + Dim msg As String + + Public Sub New(errorMessage As String) + msg = errorMessage + End Sub + + Public ReadOnly Property Message As String + Get + Return msg + End Get + End Property End Class Public Module StringUtilities - Public Function SplitString(value As String, index As Integer) As String() - If index < 0 Or index > value.Length Then - Dim BadIndex As New ErrorClass("The index is not within the string.") - Throw BadIndex - End If - Dim retVal() As String = { value.Substring(0, index - 1), - value.Substring(index) } - Return retVal - End Function + Public Function SplitString(value As String, index As Integer) As String() + If index < 0 Or index > value.Length Then + Dim BadIndex As New ErrorClass("The index is not within the string.") + Throw BadIndex + End If + Dim retVal() As String = {value.Substring(0, index - 1), + value.Substring(index)} + Return retVal + End Function End Module ' Compilation produces a compiler error like the following: ' Exceptions1.vb(27) : error BC30665: 'Throw' operand must derive from 'System.Exception'. @@ -41,8 +41,8 @@ End Module Module Example - Public Sub Main() + Public Sub Main() - End Sub + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/exceptions2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/exceptions2.vb index 9f7114f3f74e0..fa39ba42e0efb 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/exceptions2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/exceptions2.vb @@ -5,39 +5,39 @@ Option Strict On Imports System.Runtime.CompilerServices - + Public Class ErrorClass : Inherits Exception - Dim msg As String - - Public Sub New(errorMessage As String) - msg = errorMessage - End Sub - - Public Overrides ReadOnly Property Message As String - Get - Return msg - End Get - End Property + Dim msg As String + + Public Sub New(errorMessage As String) + msg = errorMessage + End Sub + + Public Overrides ReadOnly Property Message As String + Get + Return msg + End Get + End Property End Class Public Module StringUtilities - Public Function SplitString(value As String, index As Integer) As String() - If index < 0 Or index > value.Length Then - Dim BadIndex As New ErrorClass("The index is not within the string.") - Throw BadIndex - End If - Dim retVal() As String = { value.Substring(0, index - 1), - value.Substring(index) } - Return retVal - End Function + Public Function SplitString(value As String, index As Integer) As String() + If index < 0 Or index > value.Length Then + Dim BadIndex As New ErrorClass("The index is not within the string.") + Throw BadIndex + End If + Dim retVal() As String = {value.Substring(0, index - 1), + value.Substring(index)} + Return retVal + End Function End Module ' Module Example - Public Sub Main() + Public Sub Main() - End Sub + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics2.vb index de105aadec3e1..7ce398dc71314 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics2.vb @@ -2,65 +2,65 @@ Option Strict On ' - + Public Class Number(Of T As Structure) - ' Use Double as the underlying type, since its range is a superset of - ' the ranges of all numeric types except BigInteger. - Protected number As Double - - Public Sub New(value As T) - Try - Me.number = Convert.ToDouble(value) - Catch e As OverflowException - Throw New ArgumentException("value is too large.", e) - Catch e As InvalidCastException - Throw New ArgumentException("The value parameter is not numeric.", e) - End Try - End Sub + ' Use Double as the underlying type, since its range is a superset of + ' the ranges of all numeric types except BigInteger. + Protected number As Double - Public Function Add(value As T) As T - Return CType(Convert.ChangeType(number + Convert.ToDouble(value), GetType(T)), T) - End Function + Public Sub New(value As T) + Try + Me.number = Convert.ToDouble(value) + Catch e As OverflowException + Throw New ArgumentException("value is too large.", e) + Catch e As InvalidCastException + Throw New ArgumentException("The value parameter is not numeric.", e) + End Try + End Sub - Public Function Subtract(value As T) As T - Return CType(Convert.ChangeType(number - Convert.ToDouble(value), GetType(T)), T) - End Function + Public Function Add(value As T) As T + Return CType(Convert.ChangeType(number + Convert.ToDouble(value), GetType(T)), T) + End Function + + Public Function Subtract(value As T) As T + Return CType(Convert.ChangeType(number - Convert.ToDouble(value), GetType(T)), T) + End Function +End Class + +Public Class FloatingPoint(Of T As Structure) : Inherits Number(Of T) + Public Sub New(number As T) + MyBase.New(number) + If TypeOf number Is Single Or + TypeOf number Is Double Or + TypeOf number Is Decimal Then + Me.number = Convert.ToDouble(number) + Else + throw new ArgumentException("The number parameter is not a floating-point number.") + End If + End Sub End Class - -Public Class FloatingPoint(Of T As Structure) : Inherits Number(Of T) - Public Sub New(number As T) - MyBase.New(number) - If TypeOf number Is Single Or - TypeOf number Is Double Or - TypeOf number Is Decimal Then - Me.number = Convert.ToDouble(number) - Else - throw new ArgumentException("The number parameter is not a floating-point number.") - End If - End Sub -End Class ' Module Example - Public Sub Main() - Dim byt As New Number(Of Byte)(12) - Console.WriteLine(byt.Add(12)) - - Dim sbyt As New Number(Of SByte)(-3) - Console.WriteLine(sbyt.Subtract(12)) - - Dim ush As New Number(Of UShort)(16) - Console.WriteLine(ush.Add(3)) - - Dim dbl As New Number(Of Double)(Math.PI) - Console.WriteLine(dbl.Add(1.0)) - - Dim sng As New FloatingPoint(Of Single)(12.3) - Console.WriteLine(sng.Add(3.0)) - -' Dim f2 As New FloatingPoint(Of Integer)(16) -' Console.WriteLine(f2.Add(6)) - End Sub + Public Sub Main() + Dim byt As New Number(Of Byte)(12) + Console.WriteLine(byt.Add(12)) + + Dim sbyt As New Number(Of SByte)(-3) + Console.WriteLine(sbyt.Subtract(12)) + + Dim ush As New Number(Of UShort)(16) + Console.WriteLine(ush.Add(3)) + + Dim dbl As New Number(Of Double)(Math.PI) + Console.WriteLine(dbl.Add(1.0)) + + Dim sng As New FloatingPoint(Of Single)(12.3) + Console.WriteLine(sng.Add(3.0)) + + ' Dim f2 As New FloatingPoint(Of Integer)(16) + ' Console.WriteLine(f2.Add(6)) + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics2a.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics2a.vb index ea7a850f856dc..72921302fcf3c 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics2a.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics2a.vb @@ -2,44 +2,44 @@ Option Strict On ' - + Public Class Number(Of T As Structure) - ' Use Double as the underlying type, since its range is a superset of - ' the ranges of all numeric types except BigInteger. - Protected number As Double - - Public Sub New(value As T) - Try - Me.number = Convert.ToDouble(value) - Catch e As OverflowException - Throw New ArgumentException("value is too large.", e) - Catch e As InvalidCastException - Throw New ArgumentException("The value parameter is not numeric.", e) - End Try - End Sub + ' Use Double as the underlying type, since its range is a superset of + ' the ranges of all numeric types except BigInteger. + Protected number As Double - Public Function Add(value As T) As T - Return CType(Convert.ChangeType(number + Convert.ToDouble(value), GetType(T)), T) - End Function + Public Sub New(value As T) + Try + Me.number = Convert.ToDouble(value) + Catch e As OverflowException + Throw New ArgumentException("value is too large.", e) + Catch e As InvalidCastException + Throw New ArgumentException("The value parameter is not numeric.", e) + End Try + End Sub - Public Function Subtract(value As T) As T - Return CType(Convert.ChangeType(number - Convert.ToDouble(value), GetType(T)), T) - End Function + Public Function Add(value As T) As T + Return CType(Convert.ChangeType(number + Convert.ToDouble(value), GetType(T)), T) + End Function + + Public Function Subtract(value As T) As T + Return CType(Convert.ChangeType(number - Convert.ToDouble(value), GetType(T)), T) + End Function +End Class + +Public Class FloatingPoint(Of T) : Inherits Number(Of T) + Public Sub New(number As T) + MyBase.New(number) + If TypeOf number Is Single Or + TypeOf number Is Double Or + TypeOf number Is Decimal Then + Me.number = Convert.ToDouble(number) + Else + throw new ArgumentException("The number parameter is not a floating-point number.") + End If + End Sub End Class - -Public Class FloatingPoint(Of T) : Inherits Number(Of T) - Public Sub New(number As T) - MyBase.New(number) - If TypeOf number Is Single Or - TypeOf number Is Double Or - TypeOf number Is Decimal Then - Me.number = Convert.ToDouble(number) - Else - throw new ArgumentException("The number parameter is not a floating-point number.") - End If - End Sub -End Class ' The attempt to comple the example displays the following output: ' error BC32105: Type argument 'T' does not satisfy the 'Structure' ' constraint for type parameter 'T'. @@ -49,24 +49,24 @@ End Class ' Module Example - Public Sub Main() - Dim byt As New Number(Of Byte)(12) - Console.WriteLine(byt.Add(12)) - - Dim sbyt As New Number(Of SByte)(-3) - Console.WriteLine(sbyt.Subtract(12)) - - Dim ush As New Number(Of UShort)(16) - Console.WriteLine(ush.Add(3)) - - Dim dbl As New Number(Of Double)(Math.PI) - Console.WriteLine(dbl.Add(1.0)) - - Dim sng As New FloatingPoint(Of Single)(12.3) - Console.WriteLine(sng.Add(3.0)) - -' Dim f2 As New FloatingPoint(Of Integer)(16) -' Console.WriteLine(f2.Add(6)) - End Sub + Public Sub Main() + Dim byt As New Number(Of Byte)(12) + Console.WriteLine(byt.Add(12)) + + Dim sbyt As New Number(Of SByte)(-3) + Console.WriteLine(sbyt.Subtract(12)) + + Dim ush As New Number(Of UShort)(16) + Console.WriteLine(ush.Add(3)) + + Dim dbl As New Number(Of Double)(Math.PI) + Console.WriteLine(dbl.Add(1.0)) + + Dim sng As New FloatingPoint(Of Single)(12.3) + Console.WriteLine(sng.Add(3.0)) + + ' Dim f2 As New FloatingPoint(Of Integer)(16) + ' Console.WriteLine(f2.Add(6)) + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics4.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics4.vb index 4807c3b842bb3..2251bbfc6b7fd 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics4.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics4.vb @@ -2,27 +2,27 @@ Option Strict On ' - + -Public Class C1(Of T) - Protected Class N - End Class +Public Class C1(Of T) + Protected Class N + End Class - Protected Sub M1(n As C1(Of Integer).N) ' Not CLS-compliant - C1.N not - ' accessible from within C1(Of T) in all - End Sub ' languages + Protected Sub M1(n As C1(Of Integer).N) ' Not CLS-compliant - C1.N not + ' accessible from within C1(Of T) in all + End Sub ' languages - Protected Sub M2(n As C1(Of T).N) ' CLS-compliant – C1(Of T).N accessible - End Sub ' inside C1(Of T) + Protected Sub M2(n As C1(Of T).N) ' CLS-compliant – C1(Of T).N accessible + End Sub ' inside C1(Of T) End Class -Public Class C2 : Inherits C1(Of Long) - Protected Sub M3(n As C1(Of Integer).N) ' Not CLS-compliant – C1(Of Integer).N is not - End Sub ' accessible in C2 (extends C1(Of Long)) +Public Class C2 : Inherits C1(Of Long) + Protected Sub M3(n As C1(Of Integer).N) ' Not CLS-compliant – C1(Of Integer).N is not + End Sub ' accessible in C2 (extends C1(Of Long)) - Protected Sub M4(n As C1(Of Long).N) - End Sub + Protected Sub M4(n As C1(Of Long).N) + End Sub End Class ' Attempting to compile the example displays output like the following: ' error BC30508: 'n' cannot expose type 'C1(Of Integer).N' in namespace @@ -45,9 +45,9 @@ End Class Module Example - Public Sub Main() + Public Sub Main() - End Sub + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics5.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics5.vb index 16e5c3eeec947..9754f1fa64005 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics5.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/generics5.vb @@ -19,8 +19,8 @@ End Class ' Module Example - Public Sub Main() + Public Sub Main() - End Sub + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/indicator3.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/indicator3.vb index c1c7ff6379f1f..cbec34d401129 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/indicator3.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/indicator3.vb @@ -4,54 +4,54 @@ Option Strict On ' Imports System.Text - + Public Class CharacterUtilities - Public Shared Function ToUTF16(s As String) As UShort - s = s.Normalize(NormalizationForm.FormC) - Return Convert.ToUInt16(s(0)) - End Function - - Public Shared Function ToUTF16(ch As Char) As UShort - Return Convert.ToUInt16(ch) - End Function - - ' CLS-compliant alternative for ToUTF16(String). - Public Shared Function ToUTF16CodeUnit(s As String) As Integer - s = s.Normalize(NormalizationForm.FormC) - Return CInt(Convert.ToInt16(s(0))) - End Function - - ' CLS-compliant alternative for ToUTF16(Char). - Public Shared Function ToUTF16CodeUnit(ch As Char) As Integer - Return Convert.ToInt32(ch) - End Function - - Public Function HasMultipleRepresentations(s As String) As Boolean - Dim s1 As String = s.Normalize(NormalizationForm.FormC) - Return s.Equals(s1) - End Function - - Public Function GetUnicodeCodePoint(ch As Char) As Integer - If Char.IsSurrogate(ch) Then - Throw New ArgumentException("ch cannot be a high or low surrogate.") - End If - Return Char.ConvertToUtf32(ch.ToString(), 0) - End Function - - Public Function GetUnicodeCodePoint(chars() As Char) As Integer - If chars.Length > 2 Then - Throw New ArgumentException("The array has too many characters.") - End If - If chars.Length = 2 Then - If Not Char.IsSurrogatePair(chars(0), chars(1)) Then - Throw New ArgumentException("The array must contain a low and a high surrogate.") - Else - Return Char.ConvertToUtf32(chars(0), chars(1)) - End If - Else - Return Char.ConvertToUtf32(chars.ToString(), 0) - End If - End Function + Public Shared Function ToUTF16(s As String) As UShort + s = s.Normalize(NormalizationForm.FormC) + Return Convert.ToUInt16(s(0)) + End Function + + Public Shared Function ToUTF16(ch As Char) As UShort + Return Convert.ToUInt16(ch) + End Function + + ' CLS-compliant alternative for ToUTF16(String). + Public Shared Function ToUTF16CodeUnit(s As String) As Integer + s = s.Normalize(NormalizationForm.FormC) + Return CInt(Convert.ToInt16(s(0))) + End Function + + ' CLS-compliant alternative for ToUTF16(Char). + Public Shared Function ToUTF16CodeUnit(ch As Char) As Integer + Return Convert.ToInt32(ch) + End Function + + Public Function HasMultipleRepresentations(s As String) As Boolean + Dim s1 As String = s.Normalize(NormalizationForm.FormC) + Return s.Equals(s1) + End Function + + Public Function GetUnicodeCodePoint(ch As Char) As Integer + If Char.IsSurrogate(ch) Then + Throw New ArgumentException("ch cannot be a high or low surrogate.") + End If + Return Char.ConvertToUtf32(ch.ToString(), 0) + End Function + + Public Function GetUnicodeCodePoint(chars() As Char) As Integer + If chars.Length > 2 Then + Throw New ArgumentException("The array has too many characters.") + End If + If chars.Length = 2 Then + If Not Char.IsSurrogatePair(chars(0), chars(1)) Then + Throw New ArgumentException("The array must contain a low and a high surrogate.") + Else + Return Char.ConvertToUtf32(chars(0), chars(1)) + End If + Else + Return Char.ConvertToUtf32(chars.ToString(), 0) + End If + End Function End Class ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/interface2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/interface2.vb index 9465e175c59c8..7b09a40f229bc 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/interface2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/interface2.vb @@ -5,9 +5,9 @@ Option Strict On Public Interface INumber - Function Length As Integer - - Function GetUnsigned As ULong + Function Length As Integer + + Function GetUnsigned As ULong End Interface ' Attempting to compile the example displays output like the following: ' Interface2.vb(9) : warning BC40033: Non CLS-compliant 'function' is not allowed in a @@ -19,8 +19,8 @@ End Interface Module Example - Public Sub Main() + Public Sub Main() - End Sub + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/keyword1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/keyword1.vb index 8208cc13b0848..7e8647c8d8247 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/keyword1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/keyword1.vb @@ -3,18 +3,18 @@ Option Strict On ' Public Class [case] - Private _id As Guid - Private name As String - - Public Sub New(name As String) - _id = Guid.NewGuid() - Me.name = name - End Sub - - Public ReadOnly Property ClientName As String - Get - Return name - End Get - End Property + Private _id As Guid + Private name As String + + Public Sub New(name As String) + _id = Guid.NewGuid() + Me.name = name + End Sub + + Public ReadOnly Property ClientName As String + Get + Return name + End Get + End Property End Class ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/naming1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/naming1.vb index 4dca3c59d3b66..05e9efb1f3dcb 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/naming1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/naming1.vb @@ -4,26 +4,26 @@ Option Strict On ' Public Class Size - Private a1 As Double - Private a2 As Double - - Public Property Å As Double - Get - Return a1 - End Get - Set - a1 = value - End Set - End Property - - Public Property Å As Double - Get - Return a2 - End Get - Set - a2 = value - End Set - End Property + Private a1 As Double + Private a2 As Double + + Public Property Å As Double + Get + Return a1 + End Get + Set + a1 = value + End Set + End Property + + Public Property Å As Double + Get + Return a2 + End Get + Set + a2 = value + End Set + End Property End Class ' Compilation produces a compiler warning like the following: ' Naming1.vb(9) : error BC30269: 'Public Property Å As Double' has multiple definitions @@ -34,8 +34,8 @@ End Class ' Module Example - Public Sub Main() + Public Sub Main() - End Sub + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/naming3.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/naming3.vb index 8d6a737097c6c..a574100d1370c 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/naming3.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/naming3.vb @@ -5,23 +5,23 @@ Option Strict On Public Class Converter - Public Function Conversion(number As Integer) As Double - Return CDbl(number) - End Function + Public Function Conversion(number As Integer) As Double + Return CDbl(number) + End Function - Public Function Conversion(number As Integer) As Single - Return CSng(number) - End Function - - Public Function Conversion(number As Long) As Double - Return CDbl(number) - End Function - - Public ReadOnly Property Conversion As Boolean - Get - Return True - End Get - End Property + Public Function Conversion(number As Integer) As Single + Return CSng(number) + End Function + + Public Function Conversion(number As Long) As Double + Return CDbl(number) + End Function + + Public ReadOnly Property Conversion As Boolean + Get + Return True + End Get + End Property End Class ' Compilation produces a compiler error like the following: ' Naming3.vb(8) : error BC30301: 'Public Function Conversion(number As Integer) As Double' @@ -37,8 +37,8 @@ End Class ' ~~~~~~~~~~ ' Module Example - Public Sub Main() + Public Sub Main() - End Sub + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/nestedgenerics2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/nestedgenerics2.vb index c694f6482c8d8..b0e142c628a64 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/nestedgenerics2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/nestedgenerics2.vb @@ -2,42 +2,42 @@ Option Strict On ' - + Public Class Outer(Of T) - Dim value As T - - Public Sub New(value As T) - Me.value = value - End Sub - - Public Class Inner1A : Inherits Outer(Of T) - Public Sub New(value As T) - MyBase.New(value) - End Sub - End Class - - Public Class Inner1B(Of U) : Inherits Outer(Of T) - Dim value2 As U - - Public Sub New(value1 As T, value2 As U) - MyBase.New(value1) - Me.value2 = value2 - End Sub - End Class + Dim value As T + + Public Sub New(value As T) + Me.value = value + End Sub + + Public Class Inner1A : Inherits Outer(Of T) + Public Sub New(value As T) + MyBase.New(value) + End Sub + End Class + + Public Class Inner1B(Of U) : Inherits Outer(Of T) + Dim value2 As U + + Public Sub New(value1 As T, value2 As U) + MyBase.New(value1) + Me.value2 = value2 + End Sub + End Class End Class Public Module Example - Public Sub Main() - Dim inst1 As New Outer(Of String)("This") - Console.WriteLine(inst1) - - Dim inst2 As New Outer(Of String).Inner1A("Another") - Console.WriteLine(inst2) - - Dim inst3 As New Outer(Of String).Inner1B(Of Integer)("That", 2) - Console.WriteLine(inst3) - End Sub + Public Sub Main() + Dim inst1 As New Outer(Of String)("This") + Console.WriteLine(inst1) + + Dim inst2 As New Outer(Of String).Inner1A("Another") + Console.WriteLine(inst2) + + Dim inst3 As New Outer(Of String).Inner1B(Of Integer)("That", 2) + Console.WriteLine(inst3) + End Sub End Module ' The example displays the following output: ' Outer`1[System.String] diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/paramarray1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/paramarray1.vb index 1d31085ce0e6e..2be3e92e0f1f0 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/paramarray1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/paramarray1.vb @@ -5,22 +5,22 @@ Option Strict On Public Class Group - Private members() As String - - Public Sub New(ParamArray memberList() As String) - members = memberList - End Sub - - Public Overrides Function ToString() As String - Return String.Join(", ", members) - End Function + Private members() As String + + Public Sub New(ParamArray memberList() As String) + members = memberList + End Sub + + Public Overrides Function ToString() As String + Return String.Join(", ", members) + End Function End Class Module Example - Public Sub Main() - Dim gp As New Group("Matthew", "Mark", "Luke", "John") - Console.WriteLine(gp.ToString()) - End Sub + Public Sub Main() + Dim gp As New Group("Matthew", "Mark", "Luke", "John") + Console.WriteLine(gp.ToString()) + End Sub End Module ' The example displays the following output: ' Matthew, Mark, Luke, John diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/public1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/public1.vb index 602682cf74d78..8628a6e477f69 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/public1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/public1.vb @@ -1,16 +1,16 @@ ' Visual Basic .NET Document Option Strict On ' - + Public Class Person - Private personAge As UInt16 - - Public ReadOnly Property Age As UInt16 - Get - Return personAge - End Get - End Property + Private personAge As UInt16 + + Public ReadOnly Property Age As UInt16 + Get + Return personAge + End Get + End Property End Class ' The attempt to compile the example displays the following compiler warning: ' Public1.vb(9) : warning BC40027: Return type of function 'Age' is not CLS-compliant. @@ -18,4 +18,3 @@ End Class ' Public ReadOnly Property Age As UInt16 ' ~~~ ' - \ No newline at end of file diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/public2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/public2.vb index b2a9d1877fb18..ca09988b73540 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/public2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/public2.vb @@ -1,15 +1,15 @@ ' Visual Basic .NET Document Option Strict On ' - + Public Class Person - Private personAge As UInt16 - - Public ReadOnly Property Age As Int16 - Get - Return CType(personAge, Int16) - End Get - End Property + Private personAge As UInt16 + + Public ReadOnly Property Age As Int16 + Get + Return CType(personAge, Int16) + End Get + End Property End Class ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/type1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/type1.vb index bf110d333c915..0f81759f08d60 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/type1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/type1.vb @@ -6,32 +6,32 @@ Option Strict On Public Class InvoiceItem - Private invId As UInteger = 0 - Private itemId As UInteger = 0 - Private qty AS Nullable(Of UInteger) - - Public Sub New(sku As UInteger, quantity As Nullable(Of UInteger)) - itemId = sku - qty = quantity - End Sub + Private invId As UInteger = 0 + Private itemId As UInteger = 0 + Private qty AS Nullable(Of UInteger) - Public Property Quantity As Nullable(Of UInteger) - Get - Return qty - End Get - Set - qty = value - End Set - End Property + Public Sub New(sku As UInteger, quantity As Nullable(Of UInteger)) + itemId = sku + qty = quantity + End Sub - Public Property InvoiceId As UInteger - Get - Return invId - End Get - Set - invId = value - End Set - End Property + Public Property Quantity As Nullable(Of UInteger) + Get + Return qty + End Get + Set + qty = value + End Set + End Property + + Public Property InvoiceId As UInteger + Get + Return invId + End Get + Set + invId = value + End Set + End Property End Class ' The attempt to compile the example displays output similar to the following: ' Type1.vb(13) : warning BC40028: Type of parameter 'sku' is not CLS-compliant. diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/type2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/type2.vb index 29dda02700987..8d7c8e529b3ba 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/type2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/type2.vb @@ -6,35 +6,35 @@ Option Strict On Public Class InvoiceItem - Private invId As UInteger = 0 - Private itemId As UInteger = 0 - Private qty AS Nullable(Of Integer) - - Public Sub New(sku As Integer, quantity As Nullable(Of Integer)) - If sku <= 0 Then - Throw New ArgumentOutOfRangeException("The item number is zero or negative.") - End If - itemId = CUInt(sku) - qty = quantity - End Sub + Private invId As UInteger = 0 + Private itemId As UInteger = 0 + Private qty AS Nullable(Of Integer) - Public Property Quantity As Nullable(Of Integer) - Get - Return qty - End Get - Set - qty = value - End Set - End Property + Public Sub New(sku As Integer, quantity As Nullable(Of Integer)) + If sku <= 0 Then + Throw New ArgumentOutOfRangeException("The item number is zero or negative.") + End If + itemId = CUInt(sku) + qty = quantity + End Sub - Public Property InvoiceId As Integer - Get - Return CInt(invId) - End Get - Set - invId = CUInt(value) - End Set - End Property + Public Property Quantity As Nullable(Of Integer) + Get + Return qty + End Get + Set + qty = value + End Set + End Property + + Public Property InvoiceId As Integer + Get + Return CInt(invId) + End Get + Set + invId = CUInt(value) + End Set + End Property End Class ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/type3.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/type3.vb index 5c1e0f2d15926..8e6de884609c1 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/type3.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/type3.vb @@ -4,41 +4,41 @@ Option Strict On ' - _ + _ Public Class Counter - Dim ctr As UInt32 - - Public Sub New - ctr = 0 - End Sub - - Protected Sub New(ctr As UInt32) - ctr = ctr - End Sub - - Public Overrides Function ToString() As String - Return String.Format("{0}). ", ctr) - End Function - - Public ReadOnly Property Value As UInt32 - Get - Return ctr - End Get - End Property - - Public Sub Increment() - ctr += CType(1, UInt32) - End Sub + Dim ctr As UInt32 + + Public Sub New + ctr = 0 + End Sub + + Protected Sub New(ctr As UInt32) + ctr = ctr + End Sub + + Public Overrides Function ToString() As String + Return String.Format("{0}). ", ctr) + End Function + + Public ReadOnly Property Value As UInt32 + Get + Return ctr + End Get + End Property + + Public Sub Increment() + ctr += CType(1, UInt32) + End Sub End Class Public Class NonZeroCounter : Inherits Counter - Public Sub New(startIndex As Integer) - MyClass.New(CType(startIndex, UInt32)) - End Sub - - Private Sub New(startIndex As UInt32) - MyBase.New(CType(startIndex, UInt32)) - End Sub + Public Sub New(startIndex As Integer) + MyClass.New(CType(startIndex, UInt32)) + End Sub + + Private Sub New(startIndex As UInt32) + MyBase.New(CType(startIndex, UInt32)) + End Sub End Class ' Compilation produces a compiler warning like the following: ' Type3.vb(34) : warning BC40026: 'NonZeroCounter' is not CLS-compliant @@ -50,8 +50,8 @@ End Class Module Example - Public Sub Main() -'' Dim c As New NonZeroCounter(-3) - End Sub + Public Sub Main() + '' Dim c As New NonZeroCounter(-3) + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/convert1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/convert1.vb index a323cdbcd8720..2e8640cfd828a 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/convert1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/convert1.vb @@ -1,91 +1,91 @@ Option Strict On Public Module Example - Public Sub Main() - PerformConversions() - Console.WriteLine("-----") - LosePrecision() - End Sub - - Private Sub PerformConversions() - ' - ' Convert an Int32 value to a Decimal (a widening conversion). - Dim integralValue As Integer = 12534 - Dim decimalValue As Decimal = Convert.ToDecimal(integralValue) - Console.WriteLine("Converted the {0} value {1} to the {2} value {3:N2}.", - integralValue.GetType().Name, - integralValue, - decimalValue.GetType().Name, - decimalValue) + Public Sub Main() + PerformConversions() + Console.WriteLine("-----") + LosePrecision() + End Sub - ' Convert a Byte value to an Int32 value (a widening conversion). - Dim byteValue As Byte = Byte.MaxValue - Dim integralValue2 As Integer = Convert.ToInt32(byteValue) - Console.WriteLine("Converted the {0} value {1} to " + - "the {2} value {3:G}.", - byteValue.GetType().Name, - byteValue, - integralValue2.GetType().Name, - integralValue2) + Private Sub PerformConversions() + ' + ' Convert an Int32 value to a Decimal (a widening conversion). + Dim integralValue As Integer = 12534 + Dim decimalValue As Decimal = Convert.ToDecimal(integralValue) + Console.WriteLine("Converted the {0} value {1} to the {2} value {3:N2}.", + integralValue.GetType().Name, + integralValue, + decimalValue.GetType().Name, + decimalValue) - ' Convert a Double value to an Int32 value (a narrowing conversion). - Dim doubleValue As Double = 16.32513e12 - Try - Dim longValue As Long = Convert.ToInt64(doubleValue) - Console.WriteLine("Converted the {0} value {1:E} to " + - "the {2} value {3:N0}.", - doubleValue.GetType().Name, - doubleValue, - longValue.GetType().Name, - longValue) - Catch e As OverflowException - Console.WriteLine("Unable to convert the {0:E} value {1}.", - doubleValue.GetType().Name, doubleValue) - End Try - - ' Convert a signed byte to a byte (a narrowing conversion). - Dim sbyteValue As SByte = -16 - Try - Dim byteValue2 As Byte = Convert.ToByte(sbyteValue) - Console.WriteLine("Converted the {0} value {1} to " + - "the {2} value {3:G}.", - sbyteValue.GetType().Name, - sbyteValue, - byteValue2.GetType().Name, - byteValue2) - Catch e As OverflowException - Console.WriteLine("Unable to convert the {0} value {1}.", - sbyteValue.GetType().Name, sbyteValue) - End Try - ' The example displays the following output: - ' Converted the Int32 value 12534 to the Decimal value 12,534.00. - ' Converted the Byte value 255 to the Int32 value 255. - ' Converted the Double value 1.632513E+013 to the Int64 value 16,325,130,000,000. - ' Unable to convert the SByte value -16. - ' - End Sub - - Private Sub LosePrecision() - ' - Dim doubleValue As Double - - ' Convert a Double to a Decimal. - Dim decimalValue As Decimal = 13956810.96702888123451471211d - doubleValue = Convert.ToDouble(decimalValue) - Console.WriteLine("{0} converted to {1}.", decimalValue, doubleValue) + ' Convert a Byte value to an Int32 value (a widening conversion). + Dim byteValue As Byte = Byte.MaxValue + Dim integralValue2 As Integer = Convert.ToInt32(byteValue) + Console.WriteLine("Converted the {0} value {1} to " + + "the {2} value {3:G}.", + byteValue.GetType().Name, + byteValue, + integralValue2.GetType().Name, + integralValue2) - doubleValue = 42.72 - Try - Dim integerValue As Integer = Convert.ToInt32(doubleValue) - Console.WriteLine("{0} converted to {1}.", - doubleValue, integerValue) - Catch e As OverflowException - Console.WriteLine("Unable to convert {0} to an integer.", - doubleValue) - End Try - ' The example displays the following output: - ' 13956810.96702888123451471211 converted to 13956810.9670289. - ' 42.72 converted to 43. - ' - End Sub -End Module \ No newline at end of file + ' Convert a Double value to an Int32 value (a narrowing conversion). + Dim doubleValue As Double = 16.32513e12 + Try + Dim longValue As Long = Convert.ToInt64(doubleValue) + Console.WriteLine("Converted the {0} value {1:E} to " + + "the {2} value {3:N0}.", + doubleValue.GetType().Name, + doubleValue, + longValue.GetType().Name, + longValue) + Catch e As OverflowException + Console.WriteLine("Unable to convert the {0:E} value {1}.", + doubleValue.GetType().Name, doubleValue) + End Try + + ' Convert a signed byte to a byte (a narrowing conversion). + Dim sbyteValue As SByte = -16 + Try + Dim byteValue2 As Byte = Convert.ToByte(sbyteValue) + Console.WriteLine("Converted the {0} value {1} to " + + "the {2} value {3:G}.", + sbyteValue.GetType().Name, + sbyteValue, + byteValue2.GetType().Name, + byteValue2) + Catch e As OverflowException + Console.WriteLine("Unable to convert the {0} value {1}.", + sbyteValue.GetType().Name, sbyteValue) + End Try + ' The example displays the following output: + ' Converted the Int32 value 12534 to the Decimal value 12,534.00. + ' Converted the Byte value 255 to the Int32 value 255. + ' Converted the Double value 1.632513E+013 to the Int64 value 16,325,130,000,000. + ' Unable to convert the SByte value -16. + ' + End Sub + + Private Sub LosePrecision() + ' + Dim doubleValue As Double + + ' Convert a Double to a Decimal. + Dim decimalValue As Decimal = 13956810.96702888123451471211d + doubleValue = Convert.ToDouble(decimalValue) + Console.WriteLine("{0} converted to {1}.", decimalValue, doubleValue) + + doubleValue = 42.72 + Try + Dim integerValue As Integer = Convert.ToInt32(doubleValue) + Console.WriteLine("{0} converted to {1}.", + doubleValue, integerValue) + Catch e As OverflowException + Console.WriteLine("Unable to convert {0} to an integer.", + doubleValue) + End Try + ' The example displays the following output: + ' 13956810.96702888123451471211 converted to 13956810.9670289. + ' 42.72 converted to 43. + ' + End Sub +End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/explicit1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/explicit1.vb index 30e3ef86b9620..d36f9b48c11e2 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/explicit1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/explicit1.vb @@ -2,119 +2,119 @@ Option Strict On Module Example - Public Sub Main() - PerformIntegerConversion() - Console.WriteLine("-----") - PerformCustomConversion() - End Sub - - Private Sub PerformIntegerConversion() - ' - Dim number1 As Long = Integer.MaxValue + 20L - Dim number2 As UInteger = Integer.MaxValue - 1000 - Dim number3 As ULong = Integer.MaxValue - - Dim intNumber As Integer - - Try - intNumber = CInt(number1) - Console.WriteLine("After assigning a {0} value, the Integer value is {1}.", - number1.GetType().Name, intNumber) - Catch e As OverflowException - If number1 > Integer.MaxValue Then - Console.WriteLine("Conversion failed: {0} exceeds {1}.", + Public Sub Main() + PerformIntegerConversion() + Console.WriteLine("-----") + PerformCustomConversion() + End Sub + + Private Sub PerformIntegerConversion() + ' + Dim number1 As Long = Integer.MaxValue + 20L + Dim number2 As UInteger = Integer.MaxValue - 1000 + Dim number3 As ULong = Integer.MaxValue + + Dim intNumber As Integer + + Try + intNumber = CInt(number1) + Console.WriteLine("After assigning a {0} value, the Integer value is {1}.", + number1.GetType().Name, intNumber) + Catch e As OverflowException + If number1 > Integer.MaxValue Then + Console.WriteLine("Conversion failed: {0} exceeds {1}.", + number1, Integer.MaxValue) + Else + Console.WriteLine("Conversion failed: {0} is less than {1}.\n", + number1, Integer.MinValue) + End If + End Try + + Try + intNumber = CInt(number2) + Console.WriteLine("After assigning a {0} value, the Integer value is {1}.", + number2.GetType().Name, intNumber) + Catch e As OverflowException + Console.WriteLine("Conversion failed: {0} exceeds {1}.", + number2, Integer.MaxValue) + End Try + + Try + intNumber = CInt(number3) + Console.WriteLine("After assigning a {0} value, the Integer value is {1}.", + number3.GetType().Name, intNumber) + Catch e As OverflowException + Console.WriteLine("Conversion failed: {0} exceeds {1}.", number1, Integer.MaxValue) - Else - Console.WriteLine("Conversion failed: {0} is less than {1}.\n", - number1, Integer.MinValue) - End If - End Try - - Try - intNumber = CInt(number2) - Console.WriteLine("After assigning a {0} value, the Integer value is {1}.", - number2.GetType().Name, intNumber) - Catch e As OverflowException - Console.WriteLine("Conversion failed: {0} exceeds {1}.", - number2, Integer.MaxValue) - End Try - - Try - intNumber = CInt(number3) - Console.WriteLine("After assigning a {0} value, the Integer value is {1}.", - number3.GetType().Name, intNumber) - Catch e As OverflowException - Console.WriteLine("Conversion failed: {0} exceeds {1}.", - number1, Integer.MaxValue) - End Try - ' The example displays the following output: - ' Conversion failed: 2147483667 exceeds 2147483647. - ' After assigning a UInt32 value, the Integer value is 2147482647. - ' After assigning a UInt64 value, the Integer value is 2147483647. - ' - End Sub - - Private Sub PerformCustomConversion() - ' - Dim value As ByteWithSign - - Try - Dim intValue As Integer = -120 - value = CType(intValue, ByteWithSign) - Console.WriteLine(value) - Catch e As OverflowException - Console.WriteLine(e.Message) - End Try - - Try - Dim uintValue As UInteger = 1024 - value = CType(uintValue, ByteWithSign) - Console.WriteLine(value) - Catch e As OverflowException - Console.WriteLine(e.Message) - End Try - ' The example displays the following output: - ' -120 - ' '1024' is out of range of the ByteWithSign data type. - ' - End Sub + End Try + ' The example displays the following output: + ' Conversion failed: 2147483667 exceeds 2147483647. + ' After assigning a UInt32 value, the Integer value is 2147482647. + ' After assigning a UInt64 value, the Integer value is 2147483647. + ' + End Sub + + Private Sub PerformCustomConversion() + ' + Dim value As ByteWithSign + + Try + Dim intValue As Integer = -120 + value = CType(intValue, ByteWithSign) + Console.WriteLine(value) + Catch e As OverflowException + Console.WriteLine(e.Message) + End Try + + Try + Dim uintValue As UInteger = 1024 + value = CType(uintValue, ByteWithSign) + Console.WriteLine(value) + Catch e As OverflowException + Console.WriteLine(e.Message) + End Try + ' The example displays the following output: + ' -120 + ' '1024' is out of range of the ByteWithSign data type. + ' + End Sub End Module ' Public Structure ByteWithSign - Private signValue As SByte - Private value As Byte - - Private Const MaxValue As Byte = Byte.MaxValue - Private Const MinValue As Integer = -1 * Byte.MaxValue - - Public Overloads Shared Narrowing Operator CType(value As Integer) As ByteWithSign - ' Check for overflow. - If value > ByteWithSign.MaxValue Or value < ByteWithSign.MinValue Then - Throw New OverflowException(String.Format("'{0}' is out of range of the ByteWithSign data type.", value)) - End If - - Dim newValue As ByteWithSign - - newValue.signValue = CSByte(Math.Sign(value)) - newValue.value = CByte(Math.Abs(value)) - Return newValue - End Operator - - Public Overloads Shared Narrowing Operator CType(value As UInteger) As ByteWithSign - If value > ByteWithSign.MaxValue Then - Throw New OverflowException(String.Format("'{0}' is out of range of the ByteWithSign data type.", value)) - End If - - Dim NewValue As ByteWithSign - - newValue.signValue = 1 - newValue.value = CByte(value) - Return newValue - End Operator - - Public Overrides Function ToString() As String - Return (signValue * value).ToString() - End Function + Private signValue As SByte + Private value As Byte + + Private Const MaxValue As Byte = Byte.MaxValue + Private Const MinValue As Integer = -1 * Byte.MaxValue + + Public Overloads Shared Narrowing Operator CType(value As Integer) As ByteWithSign + ' Check for overflow. + If value > ByteWithSign.MaxValue Or value < ByteWithSign.MinValue Then + Throw New OverflowException(String.Format("'{0}' is out of range of the ByteWithSign data type.", value)) + End If + + Dim newValue As ByteWithSign + + newValue.signValue = CSByte(Math.Sign(value)) + newValue.value = CByte(Math.Abs(value)) + Return newValue + End Operator + + Public Overloads Shared Narrowing Operator CType(value As UInteger) As ByteWithSign + If value > ByteWithSign.MaxValue Then + Throw New OverflowException(String.Format("'{0}' is out of range of the ByteWithSign data type.", value)) + End If + + Dim NewValue As ByteWithSign + + newValue.signValue = 1 + newValue.value = CByte(value) + Return newValue + End Operator + + Public Overrides Function ToString() As String + Return (signValue * value).ToString() + End Function End Structure ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/iconvertible1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/iconvertible1.vb index 1d90652dd64df..e6960929949aa 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/iconvertible1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/iconvertible1.vb @@ -2,19 +2,19 @@ Option Strict On Module Example - Public Sub Main() - CallEII() - Console.WriteLine("-----") - - End Sub - - Private Sub CallEII() - ' - Dim codePoint As Integer = 1067 - Dim iConv As IConvertible = codePoint - Dim ch As Char = iConv.ToChar(Nothing) - Console.WriteLine("Converted {0} to {1}.", codePoint, ch) - ' - End Sub + Public Sub Main() + CallEII() + Console.WriteLine("-----") + + End Sub + + Private Sub CallEII() + ' + Dim codePoint As Integer = 1067 + Dim iConv As IConvertible = codePoint + Dim ch As Char = iConv.ToChar(Nothing) + Console.WriteLine("Converted {0} to {1}.", codePoint, ch) + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/iconvertible2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/iconvertible2.vb index 58afc04c1df94..f11351196ac8a 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/iconvertible2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/iconvertible2.vb @@ -3,249 +3,249 @@ Option Strict On ' Public MustInherit Class Temperature - Implements IConvertible - - Protected temp As Decimal - - Public Sub New(temperature As Decimal) - Me.temp = temperature - End Sub - - Public Property Value As Decimal - Get - Return Me.temp - End Get - Set - Me.temp = Value - End Set - End Property - - Public Overrides Function ToString() As String - Return temp.ToString() & "º" - End Function - - ' IConvertible implementations. - Public Function GetTypeCode() As TypeCode Implements IConvertible.GetTypeCode - Return TypeCode.Object - End Function - - Public Function ToBoolean(provider As IFormatProvider) As Boolean Implements IConvertible.ToBoolean - Throw New InvalidCastException(String.Format("Temperature-to-Boolean conversion is not supported.")) - End Function - - Public Function ToByte(provider As IFormatProvider) As Byte Implements IConvertible.ToByte - If temp < Byte.MinValue Or temp > Byte.MaxValue Then - Throw New OverflowException(String.Format("{0} is out of range of the Byte data type.", temp)) - Else - Return CByte(temp) - End If - End Function - - Public Function ToChar(provider As IFormatProvider) As Char Implements IConvertible.ToChar - Throw New InvalidCastException("Temperature-to-Char conversion is not supported.") - End Function - - Public Function ToDateTime(provider As IFormatProvider) As DateTime Implements IConvertible.ToDateTime - Throw New InvalidCastException("Temperature-to-DateTime conversion is not supported.") - End Function - - Public Function ToDecimal(provider As IFormatProvider) As Decimal Implements IConvertible.ToDecimal - Return temp - End Function - - Public Function ToDouble(provider As IFormatProvider) As Double Implements IConvertible.ToDouble - Return CDbl(temp) - End Function - - Public Function ToInt16(provider As IFormatProvider) As Int16 Implements IConvertible.ToInt16 - If temp < Int16.MinValue Or temp > Int16.MaxValue Then - Throw New OverflowException(String.Format("{0} is out of range of the Int16 data type.", temp)) - End If - Return CShort(Math.Round(temp)) - End Function - - Public Function ToInt32(provider As IFormatProvider) As Int32 Implements IConvertible.ToInt32 - If temp < Int32.MinValue Or temp > Int32.MaxValue Then - Throw New OverflowException(String.Format("{0} is out of range of the Int32 data type.", temp)) - End If - Return CInt(Math.Round(temp)) - End Function - - Public Function ToInt64(provider As IFormatProvider) As Int64 Implements IConvertible.ToInt64 - If temp < Int64.MinValue Or temp > Int64.MaxValue Then - Throw New OverflowException(String.Format("{0} is out of range of the Int64 data type.", temp)) - End If - Return CLng(Math.Round(temp)) - End Function - - Public Function ToSByte(provider As IFormatProvider) As SByte Implements IConvertible.ToSByte - If temp < SByte.MinValue Or temp > SByte.MaxValue Then - Throw New OverflowException(String.Format("{0} is out of range of the SByte data type.", temp)) - Else - Return CSByte(temp) - End If - End Function - - Public Function ToSingle(provider As IFormatProvider) As Single Implements IConvertible.ToSingle - Return CSng(temp) - End Function - - Public Overridable Overloads Function ToString(provider As IFormatProvider) As String Implements IConvertible.ToString - Return temp.ToString(provider) & " °C" - End Function - - ' If conversionType is a implemented by another IConvertible method, call it. - Public Overridable Function ToType(conversionType As Type, provider As IFormatProvider) As Object Implements IConvertible.ToType - Select Case Type.GetTypeCode(conversionType) - Case TypeCode.Boolean - Return Me.ToBoolean(provider) - Case TypeCode.Byte - Return Me.ToByte(provider) - Case TypeCode.Char - Return Me.ToChar(provider) - Case TypeCode.DateTime - Return Me.ToDateTime(provider) - Case TypeCode.Decimal - Return Me.ToDecimal(provider) - Case TypeCode.Double - Return Me.ToDouble(provider) - Case TypeCode.Empty - Throw New NullReferenceException("The target type is null.") - Case TypeCode.Int16 - Return Me.ToInt16(provider) - Case TypeCode.Int32 - Return Me.ToInt32(provider) - Case TypeCode.Int64 - Return Me.ToInt64(provider) - Case TypeCode.Object - ' Leave conversion of non-base types to derived classes. - Throw New InvalidCastException(String.Format("Cannot convert from Temperature to {0}.", _ - conversionType.Name)) - Case TypeCode.SByte - Return Me.ToSByte(provider) - Case TypeCode.Single - Return Me.ToSingle(provider) - Case TypeCode.String - Return Me.ToString(provider) - Case TypeCode.UInt16 - Return Me.ToUInt16(provider) - Case TypeCode.UInt32 - Return Me.ToUInt32(provider) - Case TypeCode.UInt64 - Return Me.ToUInt64(provider) - Case Else - Throw New InvalidCastException("Conversion not supported.") - End Select - End Function - - Public Function ToUInt16(provider As IFormatProvider) As UInt16 Implements IConvertible.ToUInt16 - If temp < UInt16.MinValue Or temp > UInt16.MaxValue Then - Throw New OverflowException(String.Format("{0} is out of range of the UInt16 data type.", temp)) - End If - Return CUShort(Math.Round(temp)) - End Function - - Public Function ToUInt32(provider As IFormatProvider) As UInt32 Implements IConvertible.ToUInt32 - If temp < UInt32.MinValue Or temp > UInt32.MaxValue Then - Throw New OverflowException(String.Format("{0} is out of range of the UInt32 data type.", temp)) - End If - Return CUInt(Math.Round(temp)) - End Function - - Public Function ToUInt64(provider As IFormatProvider) As UInt64 Implements IConvertible.ToUInt64 - If temp < UInt64.MinValue Or temp > UInt64.MaxValue Then - Throw New OverflowException(String.Format("{0} is out of range of the UInt64 data type.", temp)) - End If - Return CULng(Math.Round(temp)) - End Function + Implements IConvertible + + Protected temp As Decimal + + Public Sub New(temperature As Decimal) + Me.temp = temperature + End Sub + + Public Property Value As Decimal + Get + Return Me.temp + End Get + Set + Me.temp = Value + End Set + End Property + + Public Overrides Function ToString() As String + Return temp.ToString() & "º" + End Function + + ' IConvertible implementations. + Public Function GetTypeCode() As TypeCode Implements IConvertible.GetTypeCode + Return TypeCode.Object + End Function + + Public Function ToBoolean(provider As IFormatProvider) As Boolean Implements IConvertible.ToBoolean + Throw New InvalidCastException(String.Format("Temperature-to-Boolean conversion is not supported.")) + End Function + + Public Function ToByte(provider As IFormatProvider) As Byte Implements IConvertible.ToByte + If temp < Byte.MinValue Or temp > Byte.MaxValue Then + Throw New OverflowException(String.Format("{0} is out of range of the Byte data type.", temp)) + Else + Return CByte(temp) + End If + End Function + + Public Function ToChar(provider As IFormatProvider) As Char Implements IConvertible.ToChar + Throw New InvalidCastException("Temperature-to-Char conversion is not supported.") + End Function + + Public Function ToDateTime(provider As IFormatProvider) As DateTime Implements IConvertible.ToDateTime + Throw New InvalidCastException("Temperature-to-DateTime conversion is not supported.") + End Function + + Public Function ToDecimal(provider As IFormatProvider) As Decimal Implements IConvertible.ToDecimal + Return temp + End Function + + Public Function ToDouble(provider As IFormatProvider) As Double Implements IConvertible.ToDouble + Return CDbl(temp) + End Function + + Public Function ToInt16(provider As IFormatProvider) As Int16 Implements IConvertible.ToInt16 + If temp < Int16.MinValue Or temp > Int16.MaxValue Then + Throw New OverflowException(String.Format("{0} is out of range of the Int16 data type.", temp)) + End If + Return CShort(Math.Round(temp)) + End Function + + Public Function ToInt32(provider As IFormatProvider) As Int32 Implements IConvertible.ToInt32 + If temp < Int32.MinValue Or temp > Int32.MaxValue Then + Throw New OverflowException(String.Format("{0} is out of range of the Int32 data type.", temp)) + End If + Return CInt(Math.Round(temp)) + End Function + + Public Function ToInt64(provider As IFormatProvider) As Int64 Implements IConvertible.ToInt64 + If temp < Int64.MinValue Or temp > Int64.MaxValue Then + Throw New OverflowException(String.Format("{0} is out of range of the Int64 data type.", temp)) + End If + Return CLng(Math.Round(temp)) + End Function + + Public Function ToSByte(provider As IFormatProvider) As SByte Implements IConvertible.ToSByte + If temp < SByte.MinValue Or temp > SByte.MaxValue Then + Throw New OverflowException(String.Format("{0} is out of range of the SByte data type.", temp)) + Else + Return CSByte(temp) + End If + End Function + + Public Function ToSingle(provider As IFormatProvider) As Single Implements IConvertible.ToSingle + Return CSng(temp) + End Function + + Public Overridable Overloads Function ToString(provider As IFormatProvider) As String Implements IConvertible.ToString + Return temp.ToString(provider) & " °C" + End Function + + ' If conversionType is a implemented by another IConvertible method, call it. + Public Overridable Function ToType(conversionType As Type, provider As IFormatProvider) As Object Implements IConvertible.ToType + Select Case Type.GetTypeCode(conversionType) + Case TypeCode.Boolean + Return Me.ToBoolean(provider) + Case TypeCode.Byte + Return Me.ToByte(provider) + Case TypeCode.Char + Return Me.ToChar(provider) + Case TypeCode.DateTime + Return Me.ToDateTime(provider) + Case TypeCode.Decimal + Return Me.ToDecimal(provider) + Case TypeCode.Double + Return Me.ToDouble(provider) + Case TypeCode.Empty + Throw New NullReferenceException("The target type is null.") + Case TypeCode.Int16 + Return Me.ToInt16(provider) + Case TypeCode.Int32 + Return Me.ToInt32(provider) + Case TypeCode.Int64 + Return Me.ToInt64(provider) + Case TypeCode.Object + ' Leave conversion of non-base types to derived classes. + Throw New InvalidCastException(String.Format("Cannot convert from Temperature to {0}.", _ + conversionType.Name)) + Case TypeCode.SByte + Return Me.ToSByte(provider) + Case TypeCode.Single + Return Me.ToSingle(provider) + Case TypeCode.String + Return Me.ToString(provider) + Case TypeCode.UInt16 + Return Me.ToUInt16(provider) + Case TypeCode.UInt32 + Return Me.ToUInt32(provider) + Case TypeCode.UInt64 + Return Me.ToUInt64(provider) + Case Else + Throw New InvalidCastException("Conversion not supported.") + End Select + End Function + + Public Function ToUInt16(provider As IFormatProvider) As UInt16 Implements IConvertible.ToUInt16 + If temp < UInt16.MinValue Or temp > UInt16.MaxValue Then + Throw New OverflowException(String.Format("{0} is out of range of the UInt16 data type.", temp)) + End If + Return CUShort(Math.Round(temp)) + End Function + + Public Function ToUInt32(provider As IFormatProvider) As UInt32 Implements IConvertible.ToUInt32 + If temp < UInt32.MinValue Or temp > UInt32.MaxValue Then + Throw New OverflowException(String.Format("{0} is out of range of the UInt32 data type.", temp)) + End If + Return CUInt(Math.Round(temp)) + End Function + + Public Function ToUInt64(provider As IFormatProvider) As UInt64 Implements IConvertible.ToUInt64 + If temp < UInt64.MinValue Or temp > UInt64.MaxValue Then + Throw New OverflowException(String.Format("{0} is out of range of the UInt64 data type.", temp)) + End If + Return CULng(Math.Round(temp)) + End Function End Class Public Class TemperatureCelsius : Inherits Temperature : Implements IConvertible - Public Sub New(value As Decimal) - MyBase.New(value) - End Sub - - ' Override ToString methods. - Public Overrides Function ToString() As String - Return Me.ToString(Nothing) - End Function - - Public Overrides Function ToString(provider As IFormatProvider ) As String - Return temp.ToString(provider) + "°C" - End Function - - ' If conversionType is a implemented by another IConvertible method, call it. - Public Overrides Function ToType(conversionType As Type, provider As IFormatProvider) As Object - ' For non-objects, call base method. - If Type.GetTypeCode(conversionType) <> TypeCode.Object Then - Return MyBase.ToType(conversionType, provider) - Else - If conversionType.Equals(GetType(TemperatureCelsius)) Then - Return Me - ElseIf conversionType.Equals(GetType(TemperatureFahrenheit)) - Return New TemperatureFahrenheit(CDec(Me.temp * 9 / 5 + 32)) - ' Unspecified object type: throw an InvalidCastException. - Else - Throw New InvalidCastException(String.Format("Cannot convert from Temperature to {0}.", _ - conversionType.Name)) - End If - End If - End Function + Public Sub New(value As Decimal) + MyBase.New(value) + End Sub + + ' Override ToString methods. + Public Overrides Function ToString() As String + Return Me.ToString(Nothing) + End Function + + Public Overrides Function ToString(provider As IFormatProvider) As String + Return temp.ToString(provider) + "°C" + End Function + + ' If conversionType is a implemented by another IConvertible method, call it. + Public Overrides Function ToType(conversionType As Type, provider As IFormatProvider) As Object + ' For non-objects, call base method. + If Type.GetTypeCode(conversionType) <> TypeCode.Object Then + Return MyBase.ToType(conversionType, provider) + Else + If conversionType.Equals(GetType(TemperatureCelsius)) Then + Return Me + ElseIf conversionType.Equals(GetType(TemperatureFahrenheit)) + Return New TemperatureFahrenheit(CDec(Me.temp * 9 / 5 + 32)) + ' Unspecified object type: throw an InvalidCastException. + Else + Throw New InvalidCastException(String.Format("Cannot convert from Temperature to {0}.", _ + conversionType.Name)) + End If + End If + End Function End Class Public Class TemperatureFahrenheit : Inherits Temperature : Implements IConvertible - Public Sub New(value As Decimal) - MyBase.New(value) - End Sub - - ' Override ToString methods. - Public Overrides Function ToString() As String - Return Me.ToString(Nothing) - End Function - - Public Overrides Function ToString(provider As IFormatProvider ) As String - Return temp.ToString(provider) + "°F" - End Function - - Public Overrides Function ToType(conversionType As Type, provider As IFormatProvider) As Object - ' For non-objects, call base methood. - If Type.GetTypeCode(conversionType) <> TypeCode.Object Then - Return MyBase.ToType(conversionType, provider) - Else - ' Handle conversion between derived classes. - If conversionType.Equals(GetType(TemperatureFahrenheit)) Then - Return Me - ElseIf conversionType.Equals(GetType(TemperatureCelsius)) - Return New TemperatureCelsius(CDec((MyBase.temp - 32) * 5 / 9)) - ' Unspecified object type: throw an InvalidCastException. - Else - Throw New InvalidCastException(String.Format("Cannot convert from Temperature to {0}.", _ - conversionType.Name)) - End If - End If - End Function -End Class + Public Sub New(value As Decimal) + MyBase.New(value) + End Sub + + ' Override ToString methods. + Public Overrides Function ToString() As String + Return Me.ToString(Nothing) + End Function + + Public Overrides Function ToString(provider As IFormatProvider) As String + Return temp.ToString(provider) + "°F" + End Function + + Public Overrides Function ToType(conversionType As Type, provider As IFormatProvider) As Object + ' For non-objects, call base methood. + If Type.GetTypeCode(conversionType) <> TypeCode.Object Then + Return MyBase.ToType(conversionType, provider) + Else + ' Handle conversion between derived classes. + If conversionType.Equals(GetType(TemperatureFahrenheit)) Then + Return Me + ElseIf conversionType.Equals(GetType(TemperatureCelsius)) + Return New TemperatureCelsius(CDec((MyBase.temp - 32) * 5 / 9)) + ' Unspecified object type: throw an InvalidCastException. + Else + Throw New InvalidCastException(String.Format("Cannot convert from Temperature to {0}.", _ + conversionType.Name)) + End If + End If + End Function +End Class ' Module Example - Public Sub Main() - ' - Dim tempC1 As New TemperatureCelsius(0) - Dim tempF1 As TemperatureFahrenheit = CType(Convert.ChangeType(tempC1, GetType(TemperatureFahrenheit), Nothing), TemperatureFahrenheit) - Console.WriteLine("{0} equals {1}.", tempC1, tempF1) - Dim tempC2 As TemperatureCelsius = CType(Convert.ChangeType(tempC1, GetType(TemperatureCelsius), Nothing), TemperatureCelsius) - Console.WriteLine("{0} equals {1}.", tempC1, tempC2) - Dim tempF2 As New TemperatureFahrenheit(212) - Dim tempC3 As TEmperatureCelsius = CType(Convert.ChangeType(tempF2, GEtType(TemperatureCelsius), Nothing), TemperatureCelsius) - Console.WriteLine("{0} equals {1}.", tempF2, tempC3) - Dim tempF3 As TemperatureFahrenheit = CType(Convert.ChangeType(tempF2, GetType(TemperatureFahrenheit), Nothing), TemperatureFahrenheit) - Console.WriteLine("{0} equals {1}.", tempF2, tempF3) - ' The example displays the following output: - ' 0°C equals 32°F. - ' 0°C equals 0°C. - ' 212°F equals 100°C. - ' 212°F equals 212°F. - ' - End Sub + Public Sub Main() + ' + Dim tempC1 As New TemperatureCelsius(0) + Dim tempF1 As TemperatureFahrenheit = CType(Convert.ChangeType(tempC1, GetType(TemperatureFahrenheit), Nothing), TemperatureFahrenheit) + Console.WriteLine("{0} equals {1}.", tempC1, tempF1) + Dim tempC2 As TemperatureCelsius = CType(Convert.ChangeType(tempC1, GetType(TemperatureCelsius), Nothing), TemperatureCelsius) + Console.WriteLine("{0} equals {1}.", tempC1, tempC2) + Dim tempF2 As New TemperatureFahrenheit(212) + Dim tempC3 As TEmperatureCelsius = CType(Convert.ChangeType(tempF2, GEtType(TemperatureCelsius), Nothing), TemperatureCelsius) + Console.WriteLine("{0} equals {1}.", tempF2, tempC3) + Dim tempF3 As TemperatureFahrenheit = CType(Convert.ChangeType(tempF2, GetType(TemperatureFahrenheit), Nothing), TemperatureFahrenheit) + Console.WriteLine("{0} equals {1}.", tempF2, tempF3) + ' The example displays the following output: + ' 0°C equals 32°F. + ' 0°C equals 0°C. + ' 212°F equals 100°C. + ' 212°F equals 212°F. + ' + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/implicit1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/implicit1.vb index 8274d90fddcbc..688b4cf000a5e 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/implicit1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.conversion/vb/implicit1.vb @@ -2,85 +2,85 @@ Option Strict On Module Example - Public Sub Main() - PerformDecimalConversions() - Console.WriteLine("-----") - PerformCustomConversions() - End Sub - - Private Sub PerformDecimalConversions() - ' - Dim byteValue As Byte = 16 - Dim shortValue As Short = -1024 - Dim intValue As Integer = -1034000 - Dim longValue As Long = CLng(1024^6) - Dim ulongValue As ULong = ULong.MaxValue + Public Sub Main() + PerformDecimalConversions() + Console.WriteLine("-----") + PerformCustomConversions() + End Sub - Dim decimalValue As Decimal - - decimalValue = byteValue - Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.", - byteValue.GetType().Name, decimalValue) - - decimalValue = shortValue - Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.", - shortValue.GetType().Name, decimalValue) + Private Sub PerformDecimalConversions() + ' + Dim byteValue As Byte = 16 + Dim shortValue As Short = -1024 + Dim intValue As Integer = -1034000 + Dim longValue As Long = CLng(1024 ^ 6) + Dim ulongValue As ULong = ULong.MaxValue - decimalValue = intValue - Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.", - intValue.GetType().Name, decimalValue) + Dim decimalValue As Decimal - decimalValue = longValue - Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.", - longValue.GetType().Name, decimalValue) - - decimalValue = ulongValue - Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.", - longValue.GetType().Name, decimalValue) - ' The example displays the following output: - ' After assigning a Byte value, the Decimal value is 16. - ' After assigning a Int16 value, the Decimal value is -1024. - ' After assigning a Int32 value, the Decimal value is -1034000. - ' After assigning a Int64 value, the Decimal value is 1152921504606846976. - ' After assigning a Int64 value, the Decimal value is 18446744073709551615. - ' - End Sub - - Private Sub PerformCustomConversions() - ' - Dim sbyteValue As SByte = -120 - Dim value As ByteWithSign = sbyteValue - Console.WriteLine(value.ToString()) - value = Byte.MaxValue - Console.WriteLine(value.ToString()) - ' The example displays the following output: - ' -120 - ' 255 - ' - End Sub + decimalValue = byteValue + Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.", + byteValue.GetType().Name, decimalValue) + + decimalValue = shortValue + Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.", + shortValue.GetType().Name, decimalValue) + + decimalValue = intValue + Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.", + intValue.GetType().Name, decimalValue) + + decimalValue = longValue + Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.", + longValue.GetType().Name, decimalValue) + + decimalValue = ulongValue + Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.", + longValue.GetType().Name, decimalValue) + ' The example displays the following output: + ' After assigning a Byte value, the Decimal value is 16. + ' After assigning a Int16 value, the Decimal value is -1024. + ' After assigning a Int32 value, the Decimal value is -1034000. + ' After assigning a Int64 value, the Decimal value is 1152921504606846976. + ' After assigning a Int64 value, the Decimal value is 18446744073709551615. + ' + End Sub + + Private Sub PerformCustomConversions() + ' + Dim sbyteValue As SByte = -120 + Dim value As ByteWithSign = sbyteValue + Console.WriteLine(value.ToString()) + value = Byte.MaxValue + Console.WriteLine(value.ToString()) + ' The example displays the following output: + ' -120 + ' 255 + ' + End Sub End Module ' Public Structure ByteWithSign - Private signValue As SByte - Private value As Byte - - Public Overloads Shared Widening Operator CType(value As SByte) As ByteWithSign - Dim newValue As ByteWithSign - newValue.signValue = CSByte(Math.Sign(value)) - newValue.value = CByte(Math.Abs(value)) - Return newValue - End Operator - - Public Overloads Shared Widening Operator CType(value As Byte) As ByteWithSign - Dim NewValue As ByteWithSign - newValue.signValue = 1 - newValue.value = value - Return newValue - End Operator - - Public Overrides Function ToString() As String - Return (signValue * value).ToString() - End Function + Private signValue As SByte + Private value As Byte + + Public Overloads Shared Widening Operator CType(value As SByte) As ByteWithSign + Dim newValue As ByteWithSign + newValue.signValue = CSByte(Math.Sign(value)) + newValue.value = CByte(Math.Abs(value)) + Return newValue + End Operator + + Public Overloads Shared Widening Operator CType(value As Byte) As ByteWithSign + Dim NewValue As ByteWithSign + newValue.signValue = 1 + newValue.value = value + Return newValue + End Operator + + Public Overrides Function ToString() As String + Return (signValue * value).ToString() + End Function End Structure ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.crosslanguage/vb/stringutil.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.crosslanguage/vb/stringutil.vb index 04a80562c475c..371873d90a38f 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.crosslanguage/vb/stringutil.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.crosslanguage/vb/stringutil.vb @@ -6,33 +6,33 @@ Imports System.Collections.Generic Imports System.Runtime.CompilerServices Public Module StringLib - Private exclusions As List(Of String) - - Sub New() - Dim words() As String = { "a", "an", "and", "of", "the" } - exclusions = New List(Of String) - exclusions.AddRange(words) - End Sub - - _ - Public Function ToTitleCase(title As String) As String - Dim words() As String = title.Split() - Dim result As String = String.Empty - - For ctr As Integer = 0 To words.Length - 1 - Dim word As String = words(ctr) - If ctr = 0 OrElse Not exclusions.Contains(word.ToLower()) Then - result += word.Substring(0, 1).ToUpper() + _ - word.Substring(1).ToLower() - Else - result += word.ToLower() - End If - If ctr <= words.Length - 1 Then - result += " " - End If - Next - Return result - End Function + Private exclusions As List(Of String) + + Sub New() + Dim words() As String = {"a", "an", "and", "of", "the"} + exclusions = New List(Of String) + exclusions.AddRange(words) + End Sub + + _ + Public Function ToTitleCase(title As String) As String + Dim words() As String = title.Split() + Dim result As String = String.Empty + + For ctr As Integer = 0 To words.Length - 1 + Dim word As String = words(ctr) + If ctr = 0 OrElse Not exclusions.Contains(word.ToLower()) Then + result += word.Substring(0, 1).ToUpper() + _ + word.Substring(1).ToLower() + Else + result += word.ToLower() + End If + If ctr <= words.Length - 1 Then + result += " " + End If + Next + Return result + End Function End Module ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.crosslanguage/vb/useutilities1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.crosslanguage/vb/useutilities1.vb index 32085e5ae344a..9e4331c665f26 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.crosslanguage/vb/useutilities1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.crosslanguage/vb/useutilities1.vb @@ -6,13 +6,13 @@ Imports System.Runtime.CompilerServices ' Module Example - Public Sub Main() - Dim dbl As Double = 0.0 - Double.Epsilon - Console.WriteLine(NumericLib.NearZero(dbl)) - - Dim s As String = "war and peace" - Console.WriteLine(s.ToTitleCase()) - End Sub + Public Sub Main() + Dim dbl As Double = 0.0 - Double.Epsilon + Console.WriteLine(NumericLib.NearZero(dbl)) + + Dim s As String = "war and peace" + Console.WriteLine(s.ToTitleCase()) + End Sub End Module ' The example displays the following output: ' True @@ -20,54 +20,54 @@ End Module ' Public Module StringLib - Private exclusions As List(Of String) - - Sub New() - Dim words() As String = { "a", "an", "and", "of", "the" } - exclusions = New List(Of String) - exclusions.AddRange(words) - End Sub - - _ - Public Function ToTitleCase(title As String) As String - Dim words() As String = title.Split() - Dim result As String = String.Empty - - For ctr As Integer = 0 To words.Length - 1 - Dim word As String = words(ctr) - If ctr = 0 OrElse Not exclusions.Contains(word.ToLower()) Then - result += word.Substring(0, 1).ToUpper() + _ - word.Substring(1).ToLower() - Else - result += word.ToLower() - End If - If ctr <= words.Length - 1 Then - result += " " - End If - Next - Return result - End Function + Private exclusions As List(Of String) + + Sub New() + Dim words() As String = {"a", "an", "and", "of", "the"} + exclusions = New List(Of String) + exclusions.AddRange(words) + End Sub + + _ + Public Function ToTitleCase(title As String) As String + Dim words() As String = title.Split() + Dim result As String = String.Empty + + For ctr As Integer = 0 To words.Length - 1 + Dim word As String = words(ctr) + If ctr = 0 OrElse Not exclusions.Contains(word.ToLower()) Then + result += word.Substring(0, 1).ToUpper() + _ + word.Substring(1).ToLower() + Else + result += word.ToLower() + End If + If ctr <= words.Length - 1 Then + result += " " + End If + Next + Return result + End Function End Module -Public Module NumericLib - _ - Public Function IsEven(number As IConvertible) As Boolean - If TypeOf(number) Is Byte OrElse - TypeOf(number) Is SByte OrElse - TypeOf(number) Is Int16 OrElse - TypeOf(number) Is UInt16 OrElse - TypeOf(number) Is Int32 OrElse - TypeOf(number) Is UInt32 OrElse - TypeOf(number) Is Int64 Then - Return CLng(number) Mod 2 = 0 - ElseIf TypeOf(number) Is UInt64 Then - return CULng(number) Mod 2 = 0 - Else - Throw New NotSupportedException("IsEven called for a non-integer value.") - End If - End Function - - Public Function NearZero(number As Double) As Boolean - Return number < .00001 - End Function -End Module \ No newline at end of file +Public Module NumericLib + _ + Public Function IsEven(number As IConvertible) As Boolean + If TypeOf (number) Is Byte OrElse + TypeOf (number) Is SByte OrElse + TypeOf (number) Is Int16 OrElse + TypeOf (number) Is UInt16 OrElse + TypeOf (number) Is Int32 OrElse + TypeOf (number) Is UInt32 OrElse + TypeOf (number) Is Int64 Then + Return CLng(number) Mod 2 = 0 + ElseIf TypeOf (number) Is UInt64 Then + return CULng(number) Mod 2 = 0 + Else + Throw New NotSupportedException("IsEven called for a non-integer value.") + End If + End Function + + Public Function NearZero(number As Double) As Boolean + Return number < .00001 + End Function +End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/base1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/base1.vb index eee7553a95a37..323efdda86710 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/base1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/base1.vb @@ -70,10 +70,10 @@ End Class ' Module Example - Public Sub Main() - Dim d As New DisposableStreamResource("C:\Windows\Explorer.exe") - Console.WriteLine(d.Size.ToString("N0")) - d.Dispose() - End Sub + Public Sub Main() + Dim d As New DisposableStreamResource("C:\Windows\Explorer.exe") + Console.WriteLine(d.Size.ToString("N0")) + d.Dispose() + End Sub End Module diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/derived1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/derived1.vb index ace32cc808525..45131225987a5 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/derived1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/derived1.vb @@ -57,85 +57,85 @@ End Class ' Module Example - Public Sub Main() - Dim d As New DisposableStreamResource2("C:\Windows\Explorer.exe") - d.WriteFileInfo() - d.Dispose() - End Sub + Public Sub Main() + Dim d As New DisposableStreamResource2("C:\Windows\Explorer.exe") + d.WriteFileInfo() + d.Dispose() + End Sub End Module Public Class DisposableStreamResource : Implements IDisposable - ' Define constants. - Protected Const GENERIC_READ As UInteger = &H80000000ui - Protected Const FILE_SHARE_READ As UInteger = &H0000000i - Protected Const OPEN_EXISTING As UInteger = 3 - Protected Const FILE_ATTRIBUTE_NORMAL As UInteger = &H80 - Protected INVALID_HANDLE_VALUE As New IntPtr(-1) - Private Const INVALID_FILE_SIZE As Integer = &HFFFFFFFF - - ' Define Windows APIs. - Protected Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" ( - lpFileName As String, dwDesiredAccess As UInt32, - dwShareMode As UInt32, lpSecurityAttributes As IntPtr, - dwCreationDisposition As UInt32, dwFlagsAndAttributes As UInt32, - hTemplateFile As IntPtr) As IntPtr - Private Declare Function GetFileSize Lib "kernel32" (hFile As SafeFileHandle, - ByRef lpFileSizeHigh As Integer) As Integer - - ' Define locals. - Private disposed As Boolean = False - Private safeHandle As SafeFileHandle - Private bufferSize As Long - Private upperWord As Integer - - Public Sub New(filename As String) - If filename Is Nothing Then - Throw New ArgumentNullException("The filename cannot be null.") - Else If filename = "" - Throw New ArgumentException("The filename cannot be an empty string.") - End If - - Dim handle As IntPtr = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, - IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, - IntPtr.Zero) - If handle <> INVALID_HANDLE_VALUE Then - safeHandle = New SafeFileHandle(handle, True) - Else - Throw New FileNotFoundException(String.Format("Cannot open '{0}'", filename)) - End If - - ' Get file size. - bufferSize = GetFileSize(safeHandle, upperWord) - If bufferSize = INVALID_FILE_SIZE Then - bufferSize = -1 - Else If upperWord > 0 Then - bufferSize = (CLng(upperWord) << 32) + bufferSize - End If - End Sub - - Public ReadOnly Property Size As Long - Get - Return bufferSize - End Get - End Property - - Public Sub Dispose() _ - Implements IDisposable.Dispose - Dispose(True) - GC.SuppressFinalize(Me) - End Sub - - Protected Overridable Sub Dispose(disposing As Boolean) - If disposed Then Exit Sub - - ' Dispose of managed resources here. - If disposing Then - safeHandle.Dispose() - End If - - ' Dispose of any unmanaged resources not wrapped in safe handles. - - disposed = True - End Sub + ' Define constants. + Protected Const GENERIC_READ As UInteger = &H80000000ui + Protected Const FILE_SHARE_READ As UInteger = &H0000000i + Protected Const OPEN_EXISTING As UInteger = 3 + Protected Const FILE_ATTRIBUTE_NORMAL As UInteger = &H80 + Protected INVALID_HANDLE_VALUE As New IntPtr(-1) + Private Const INVALID_FILE_SIZE As Integer = &HFFFFFFFF + + ' Define Windows APIs. + Protected Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" ( + lpFileName As String, dwDesiredAccess As UInt32, + dwShareMode As UInt32, lpSecurityAttributes As IntPtr, + dwCreationDisposition As UInt32, dwFlagsAndAttributes As UInt32, + hTemplateFile As IntPtr) As IntPtr + Private Declare Function GetFileSize Lib "kernel32" (hFile As SafeFileHandle, + ByRef lpFileSizeHigh As Integer) As Integer + + ' Define locals. + Private disposed As Boolean = False + Private safeHandle As SafeFileHandle + Private bufferSize As Long + Private upperWord As Integer + + Public Sub New(filename As String) + If filename Is Nothing Then + Throw New ArgumentNullException("The filename cannot be null.") + Else If filename = "" + Throw New ArgumentException("The filename cannot be an empty string.") + End If + + Dim handle As IntPtr = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, + IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, + IntPtr.Zero) + If handle <> INVALID_HANDLE_VALUE Then + safeHandle = New SafeFileHandle(handle, True) + Else + Throw New FileNotFoundException(String.Format("Cannot open '{0}'", filename)) + End If + + ' Get file size. + bufferSize = GetFileSize(safeHandle, upperWord) + If bufferSize = INVALID_FILE_SIZE Then + bufferSize = -1 + Else If upperWord > 0 Then + bufferSize = (CLng(upperWord) << 32) + bufferSize + End If + End Sub + + Public ReadOnly Property Size As Long + Get + Return bufferSize + End Get + End Property + + Public Sub Dispose() _ + Implements IDisposable.Dispose + Dispose(True) + GC.SuppressFinalize(Me) + End Sub + + Protected Overridable Sub Dispose(disposing As Boolean) + If disposed Then Exit Sub + + ' Dispose of managed resources here. + If disposing Then + safeHandle.Dispose() + End If + + ' Dispose of any unmanaged resources not wrapped in safe handles. + + disposed = True + End Sub End Class diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/disposable1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/disposable1.vb index 51d9abcd7e6e7..048588afd118f 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/disposable1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/disposable1.vb @@ -1,4 +1,4 @@ -' +' Public NotInheritable Class Foo Implements IDisposable @@ -12,4 +12,4 @@ Public NotInheritable Class Foo _bar.Dispose() End Sub End Class -' \ No newline at end of file +' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/dispose1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/dispose1.vb index 1630a5437ea6b..d2b0df3fe5fbd 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/dispose1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/dispose1.vb @@ -2,26 +2,26 @@ Option Strict On Module Example - Public Sub Main() + Public Sub Main() - End Sub + End Sub End Module Public Class Disposable : Implements IDisposable - ' - Public Sub Dispose() _ - Implements IDisposable.Dispose - ' Dispose of unmanaged resources. - Dispose(True) - ' Suppress finalization. - GC.SuppressFinalize(Me) - End Sub - ' + ' + Public Sub Dispose() _ + Implements IDisposable.Dispose + ' Dispose of unmanaged resources. + Dispose(True) + ' Suppress finalization. + GC.SuppressFinalize(Me) + End Sub + ' - ' - Protected Overridable Sub Dispose(disposing As Boolean) - End Sub - ' + ' + Protected Overridable Sub Dispose(disposing As Boolean) + End Sub + ' -End Class \ No newline at end of file +End Class diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/using1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/using1.vb index 6cfb9523df6a3..7dcc83df1abe9 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/using1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/using1.vb @@ -5,17 +5,17 @@ Option Strict On Imports System.IO Module Example - Public Sub Main() - Dim buffer(49) As Char - Using s As New StreamReader("File1.txt") - Dim charsRead As Integer - Do While s.Peek() <> -1 - charsRead = s.Read(buffer, 0, buffer.Length) - ' - ' Process characters read. - ' - Loop - End Using - End Sub + Public Sub Main() + Dim buffer(49) As Char + Using s As New StreamReader("File1.txt") + Dim charsRead As Integer + Do While s.Peek() <> -1 + charsRead = s.Read(buffer, 0, buffer.Length) + ' + ' Process characters read. + ' + Loop + End Using + End Sub End Module ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/using2.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/using2.vb index f31f914bfbca0..422c608364c27 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/using2.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/using2.vb @@ -5,25 +5,25 @@ Option Strict On Imports System.IO Module Example - Public Sub Main() - Dim buffer(49) As Char - Dim s As StreamReader = Nothing - - Try - s = New StreamReader("File1.txt") - Dim charsRead As Integer - Do While s.Peek() <> -1 - charsRead = s.Read(buffer, 0, buffer.Length) - ' - ' Process characters read. - ' - Loop - Finally - ' If non-null, call the object's Dispose method. - If s IsNot Nothing - s.Dispose() - End If - End Try - End Sub + Public Sub Main() + Dim buffer(49) As Char + Dim s As StreamReader = Nothing + + Try + s = New StreamReader("File1.txt") + Dim charsRead As Integer + Do While s.Peek() <> -1 + charsRead = s.Read(buffer, 0, buffer.Length) + ' + ' Process characters read. + ' + Loop + Finally + ' If non-null, call the object's Dispose method. + If s IsNot Nothing + s.Dispose() + End If + End Try + End Sub End Module ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/using3.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/using3.vb index d734b96831855..f1c6c178ca0aa 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/using3.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.disposable/vb/using3.vb @@ -5,22 +5,22 @@ Option Strict On Imports System.IO Module Example - Public Sub Main() - Dim buffer(49) As Char -'' Dim s As New StreamReader("File1.txt") -With s As New StreamReader("File1.txt") + Public Sub Main() + Dim buffer(49) As Char + '' Dim s As New StreamReader("File1.txt") + With s As New StreamReader("File1.txt") Try - Dim charsRead As Integer - Do While s.Peek() <> -1 - charsRead = s.Read(buffer, 0, buffer.Length) - ' - ' Process characters read. - ' - Loop - Finally - If s IsNot Nothing Then DirectCast(s, IDisposable).Dispose() - End Try -End With - End Sub + Dim charsRead As Integer + Do While s.Peek() <> -1 + charsRead = s.Read(buffer, 0, buffer.Length) + ' + ' Process characters read. + ' + Loop + Finally + If s IsNot Nothing Then DirectCast(s, IDisposable).Dispose() + End Try + End With + End Sub End Module ' diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.encoding/vb/bestfit1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.encoding/vb/bestfit1.vb index c13855c5a702b..d734dbab28a2e 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.encoding/vb/bestfit1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.encoding/vb/bestfit1.vb @@ -5,39 +5,39 @@ Option Strict On Imports System.Text Module Example - Public Sub Main() - ' Get an encoding for code page 1252 (Western Europe character set). - Dim cp1252 As Encoding = Encoding.GetEncoding(1252) - - ' Define and display a string. - Dim str As String = String.Format("{0} {1} {2}", ChrW(&h24c8), ChrW(&H2075), ChrW(&h221E)) - Console.WriteLine("Original string: " + str) - Console.Write("Code points in string: ") - For Each ch In str - Console.Write("{0} ", Convert.ToUInt16(ch).ToString("X4")) - Next - Console.WriteLine() - Console.WriteLine() - - ' Encode a Unicode string. - Dim bytes() As Byte = cp1252.GetBytes(str) - Console.Write("Encoded bytes: ") - For Each byt In bytes - Console.Write("{0:X2} ", byt) - Next - Console.WriteLine() - Console.WriteLine() - - ' Decode the string. - Dim str2 As String = cp1252.GetString(bytes) - Console.WriteLine("String round-tripped: {0}", str.Equals(str2)) - If Not str.Equals(str2) Then - Console.WriteLine(str2) - For Each ch In str2 + Public Sub Main() + ' Get an encoding for code page 1252 (Western Europe character set). + Dim cp1252 As Encoding = Encoding.GetEncoding(1252) + + ' Define and display a string. + Dim str As String = String.Format("{0} {1} {2}", ChrW(&h24c8), ChrW(&H2075), ChrW(&h221E)) + Console.WriteLine("Original string: " + str) + Console.Write("Code points in string: ") + For Each ch In str Console.Write("{0} ", Convert.ToUInt16(ch).ToString("X4")) - Next - End If - End Sub + Next + Console.WriteLine() + Console.WriteLine() + + ' Encode a Unicode string. + Dim bytes() As Byte = cp1252.GetBytes(str) + Console.Write("Encoded bytes: ") + For Each byt In bytes + Console.Write("{0:X2} ", byt) + Next + Console.WriteLine() + Console.WriteLine() + + ' Decode the string. + Dim str2 As String = cp1252.GetString(bytes) + Console.WriteLine("String round-tripped: {0}", str.Equals(str2)) + If Not str.Equals(str2) Then + Console.WriteLine(str2) + For Each ch In str2 + Console.Write("{0} ", Convert.ToUInt16(ch).ToString("X4")) + Next + End If + End Sub End Module ' The example displays the following output: ' Original string: Ⓢ ⁵ ∞ diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.encoding/vb/bestfit1a.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.encoding/vb/bestfit1a.vb index 99ed3100bdeb3..41ac80329ec64 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.encoding/vb/bestfit1a.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.encoding/vb/bestfit1a.vb @@ -5,29 +5,29 @@ Option Strict On Imports System.Text Module Example - Public Sub Main() - Dim cp1252r As Encoding = Encoding.GetEncoding(1252, - New EncoderReplacementFallback("*"), - New DecoderReplacementFallback("*")) - - Dim str1 As String = String.Format("{0} {1} {2}", ChrW(&h24C8), ChrW(&h2075), ChrW(&h221E)) - Console.WriteLine(str1) - For Each ch In str1 - Console.Write("{0} ", Convert.ToUInt16(ch).ToString("X4")) - Next - Console.WriteLine() + Public Sub Main() + Dim cp1252r As Encoding = Encoding.GetEncoding(1252, + New EncoderReplacementFallback("*"), + New DecoderReplacementFallback("*")) - Dim bytes() As Byte = cp1252r.GetBytes(str1) - Dim str2 As String = cp1252r.GetString(bytes) - Console.WriteLine("Round-trip: {0}", str1.Equals(str2)) - If Not str1.Equals(str2) Then - Console.WriteLine(str2) - For Each ch In str2 + Dim str1 As String = String.Format("{0} {1} {2}", ChrW(&h24C8), ChrW(&h2075), ChrW(&h221E)) + Console.WriteLine(str1) + For Each ch In str1 Console.Write("{0} ", Convert.ToUInt16(ch).ToString("X4")) - Next - Console.WriteLine() - End If - End Sub + Next + Console.WriteLine() + + Dim bytes() As Byte = cp1252r.GetBytes(str1) + Dim str2 As String = cp1252r.GetString(bytes) + Console.WriteLine("Round-trip: {0}", str1.Equals(str2)) + If Not str1.Equals(str2) Then + Console.WriteLine(str2) + For Each ch In str2 + Console.Write("{0} ", Convert.ToUInt16(ch).ToString("X4")) + Next + Console.WriteLine() + End If + End Sub End Module ' The example displays the following output: ' Ⓢ ⁵ ∞ diff --git a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.encoding/vb/custom1.vb b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.encoding/vb/custom1.vb index d3e76a6e5f3f9..a86ef011002cd 100644 --- a/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.encoding/vb/custom1.vb +++ b/samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.encoding/vb/custom1.vb @@ -4,146 +4,146 @@ Imports System.Collections.Generic Module Module1 - Sub Main() - Dim enc As Encoding = Encoding.GetEncoding("us-ascii", New CustomMapper(), New DecoderExceptionFallback()) - - Dim str1 As String = String.Format("{0} {1} {2}", ChrW(&H24C8), ChrW(&H2075), ChrW(&H221E)) - Console.WriteLine(str1) - For ctr As Integer = 0 To str1.Length - 1 - Console.Write("{0} ", Convert.ToUInt16(str1(ctr)).ToString("X4")) - If ctr = str1.Length - 1 Then Console.WriteLine() - Next - Console.WriteLine() - - ' Encode the original string using the ASCII encoder. - Dim bytes() As Byte = enc.GetBytes(str1) - Console.Write("Encoded bytes: ") - For Each byt In bytes - Console.Write("{0:X2} ", byt) - Next - Console.WriteLine() - Console.WriteLine() - - ' Decode the ASCII bytes. - Dim str2 As String = enc.GetString(bytes) - Console.WriteLine("Round-trip: {0}", str1.Equals(str2)) - If Not str1.Equals(str2) Then - Console.WriteLine(str2) - For Each ch In str2 - Console.Write("{0} ", Convert.ToUInt16(ch).ToString("X4")) - Next - Console.WriteLine() - End If - End Sub + Sub Main() + Dim enc As Encoding = Encoding.GetEncoding("us-ascii", New CustomMapper(), New DecoderExceptionFallback()) + + Dim str1 As String = String.Format("{0} {1} {2}", ChrW(&H24C8), ChrW(&H2075), ChrW(&H221E)) + Console.WriteLine(str1) + For ctr As Integer = 0 To str1.Length - 1 + Console.Write("{0} ", Convert.ToUInt16(str1(ctr)).ToString("X4")) + If ctr = str1.Length - 1 Then Console.WriteLine() + Next + Console.WriteLine() + + ' Encode the original string using the ASCII encoder. + Dim bytes() As Byte = enc.GetBytes(str1) + Console.Write("Encoded bytes: ") + For Each byt In bytes + Console.Write("{0:X2} ", byt) + Next + Console.WriteLine() + Console.WriteLine() + + ' Decode the ASCII bytes. + Dim str2 As String = enc.GetString(bytes) + Console.WriteLine("Round-trip: {0}", str1.Equals(str2)) + If Not str1.Equals(str2) Then + Console.WriteLine(str2) + For Each ch In str2 + Console.Write("{0} ", Convert.ToUInt16(ch).ToString("X4")) + Next + Console.WriteLine() + End If + End Sub End Module ' ' Public Class CustomMapper : Inherits EncoderFallback - Public DefaultString As String - Friend mapping As Dictionary(Of UShort, ULong) - - Public Sub New() - Me.New("?") - End Sub - - Public Sub New(ByVal defaultString As String) - Me.DefaultString = defaultString - - ' Create table of mappings - mapping = New Dictionary(Of UShort, ULong) - mapping.Add(&H24C8, &H53) - mapping.Add(&H2075, &H35) - mapping.Add(&H221E, &H49004E0046) - End Sub - - Public Overrides Function CreateFallbackBuffer() As System.Text.EncoderFallbackBuffer - Return New CustomMapperFallbackBuffer(Me) - End Function - - Public Overrides ReadOnly Property MaxCharCount As Integer - Get - Return 3 - End Get - End Property + Public DefaultString As String + Friend mapping As Dictionary(Of UShort, ULong) + + Public Sub New() + Me.New("?") + End Sub + + Public Sub New(ByVal defaultString As String) + Me.DefaultString = defaultString + + ' Create table of mappings + mapping = New Dictionary(Of UShort, ULong) + mapping.Add(&H24C8, &H53) + mapping.Add(&H2075, &H35) + mapping.Add(&H221E, &H49004E0046) + End Sub + + Public Overrides Function CreateFallbackBuffer() As System.Text.EncoderFallbackBuffer + Return New CustomMapperFallbackBuffer(Me) + End Function + + Public Overrides ReadOnly Property MaxCharCount As Integer + Get + Return 3 + End Get + End Property End Class ' ' Public Class CustomMapperFallbackBuffer : Inherits EncoderFallbackBuffer - Dim count As Integer = -1 ' Number of characters to return - Dim index As Integer = -1 ' Index of character to return - Dim fb As CustomMapper - Dim charsToReturn As String - - Public Sub New(ByVal fallback As CustomMapper) - MyBase.New() - Me.fb = fallback - End Sub - - Public Overloads Overrides Function Fallback(ByVal charUnknownHigh As Char, ByVal charUnknownLow As Char, ByVal index As Integer) As Boolean - ' Do not try to map surrogates to ASCII. - Return False - End Function - - Public Overloads Overrides Function Fallback(ByVal charUnknown As Char, ByVal index As Integer) As Boolean - ' Return false if there are already characters to map. - If count >= 1 Then Return False - - ' Determine number of characters to return. - charsToReturn = String.Empty - - Dim key As UShort = Convert.ToUInt16(charUnknown) - If fb.mapping.ContainsKey(key) Then - Dim bytes() As Byte = BitConverter.GetBytes(fb.mapping.Item(key)) - Dim ctr As Integer - For Each byt In bytes - If byt > 0 Then - ctr += 1 - charsToReturn += Chr(byt) - End If - Next - count = ctr - Else - ' Return default. - charsToReturn = fb.DefaultString - count = 1 - End If - Me.index = charsToReturn.Length - 1 - - Return True - End Function - - Public Overrides Function GetNextChar() As Char - ' We'll return a character if possible, so subtract from the count of chars to return. - count -= 1 - ' If count is less than zero, we've returned all characters. - If count < 0 Then Return ChrW(0) - - Me.index -= 1 - Return charsToReturn(Me.index + 1) - End Function - - Public Overrides Function MovePrevious() As Boolean - ' Original: if count >= -1 and pos >= 0 - If count >= -1 Then - count += 1 - Return True - Else - Return False - End If - End Function - - Public Overrides ReadOnly Property Remaining As Integer - Get - Return If(count < 0, 0, count) - End Get - End Property - - Public Overrides Sub Reset() - count = -1 - index = -1 - End Sub + Dim count As Integer = -1 ' Number of characters to return + Dim index As Integer = -1 ' Index of character to return + Dim fb As CustomMapper + Dim charsToReturn As String + + Public Sub New(ByVal fallback As CustomMapper) + MyBase.New() + Me.fb = fallback + End Sub + + Public Overloads Overrides Function Fallback(ByVal charUnknownHigh As Char, ByVal charUnknownLow As Char, ByVal index As Integer) As Boolean + ' Do not try to map surrogates to ASCII. + Return False + End Function + + Public Overloads Overrides Function Fallback(ByVal charUnknown As Char, ByVal index As Integer) As Boolean + ' Return false if there are already characters to map. + If count >= 1 Then Return False + + ' Determine number of characters to return. + charsToReturn = String.Empty + + Dim key As UShort = Convert.ToUInt16(charUnknown) + If fb.mapping.ContainsKey(key) Then + Dim bytes() As Byte = BitConverter.GetBytes(fb.mapping.Item(key)) + Dim ctr As Integer + For Each byt In bytes + If byt > 0 Then + ctr += 1 + charsToReturn += Chr(byt) + End If + Next + count = ctr + Else + ' Return default. + charsToReturn = fb.DefaultString + count = 1 + End If + Me.index = charsToReturn.Length - 1 + + Return True + End Function + + Public Overrides Function GetNextChar() As Char + ' We'll return a character if possible, so subtract from the count of chars to return. + count -= 1 + ' If count is less than zero, we've returned all characters. + If count < 0 Then Return ChrW(0) + + Me.index -= 1 + Return charsToReturn(Me.index + 1) + End Function + + Public Overrides Function MovePrevious() As Boolean + ' Original: if count >= -1 and pos >= 0 + If count >= -1 Then + count += 1 + Return True + Else + Return False + End If + End Function + + Public Overrides ReadOnly Property Remaining As Integer + Get + Return If(count < 0, 0, count) + End Get + End Property + + Public Overrides Sub Reset() + count = -1 + index = -1 + End Sub End Class '