1- '<snippet1>
2- ' Sample for String.IsInterned(String)
1+ ' Sample for String.IsInterned(String)
32Imports System.Text
4- Imports System.Runtime.CompilerServices
5-
6- ' In the .NET Framework 2.0 the following attribute declaration allows you to
7- ' avoid the use of the interning when you use NGEN.exe to compile an assembly
8- ' to the native image cache.
9- < Assembly : CompilationRelaxations(CompilationRelaxations.NoStringInterning)>
10- Class Sample
11- Public Shared Sub Main()
12- ' String str1 is known at compile time, and is automatically interned.
13- Dim str1 As [String] = "abcd"
14-
15- ' Constructed string, str2, is not explicitly or automatically interned.
16- Dim str2 As [String] = New StringBuilder().Append( "wx" ).Append( "yz" ).ToString()
17- Console.WriteLine()
18- Test( 1 , str1)
19- Test( 2 , str2)
20- End Sub
213
22- Public Shared Sub Test( ByVal sequence As Integer , ByVal str As [String])
23- Console.Write( "{0}) The string, '" , sequence)
24- Dim strInterned As [String] = [String].IsInterned(str)
25- If strInterned Is Nothing Then
26- Console.WriteLine( "{0}', is not interned." , str)
27- Else
28- Console.WriteLine( "{0}', is interned." , strInterned)
29- End If
30- End Sub
31- End Class
4+ Module IsInExample
5+ Public Sub Run()
6+ '<snippet1>
7+
8+ ' Constructed strings are not automatically interned.
9+ Dim s1 As String = New StringBuilder().Append( "My" ).Append( "Test" ).ToString()
10+ Dim s2 As String = New StringBuilder().Append( "My" ).Append( "Test" ).ToString()
3211
33- 'This example produces the following results:
12+ ' Neither string is in the intern pool yet.
13+ Console.WriteLine( $"Is s1 interned? {String.IsInterned(s1) IsNot Nothing}" )
14+ Console.WriteLine( $"Is s2 interned? {String.IsInterned(s2) IsNot Nothing}" )
3415
35- '1) The string, 'abcd', is interned .
36- '2) The string, 'wxyz', is not interned.
16+ ' Intern s1 explicitly .
17+ Dim i1 As String = String .Intern(s1)
3718
38- 'If you use NGEN.exe to compile the assembly to the native image cache, this
39- 'example produces the following results:
19+ ' Now s2 can be found in the intern pool.
20+ Dim i2 As String = String .IsInterned(s2)
4021
41- '1) The string, 'abcd', is not interned.
42- '2) The string, 'wxyz', is not interned.
43- '</snippet1>
22+ Console.WriteLine( $"Is s2 interned after interning s1? {i2 IsNot Nothing}" )
23+ Console.WriteLine( $"Are i1 and i2 the same reference? {Object.ReferenceEquals(i1, i2)}" )
24+
25+ ' This example produces the following results:
26+ '
27+ ' Is s1 interned? False
28+ ' Is s2 interned? False
29+ ' Is s2 interned after interning s1? True
30+ ' Are i1 and i2 the same reference? True
31+
32+ '</snippet1>
33+ End Sub
34+ End Module
0 commit comments