views:

123

answers:

1

I used to write this:

Private Sub Example()
Static CachedPeople As List(Of MyApp.Person)
If CachedPeople Is Nothing Then
    CachedPeople = New List(Of MyApp.Person)
End If
...rest of code...
End Sub

But then wondered if I could reduce this to:

Private Sub Example()
Static CachedPeople As New List(Of MyApp.Person)
...rest of code...
End Sub

The question is, will the "New" bit only be executed once when the function is first executed but in the next call, it will already exist.

Cheers, Rob.

+7  A: 

It'll be executed only once and on next function call, it'll reference the same object, as you mentioned. Your first snippet is not thread-safe, by the way. If two threads call your function at the same time, they might end up running the constructor twice, which is not what you want. Using the second snippet relieves you from manually locking and ensuring thread safety, as the compiler generates the appropriate code for you.

Note that if you had declared it as

Static x As List(Of String)
x = New List(Of String)

It would have been recreated each time.

Mehrdad Afshari
The code comes from an ASP.NET web app within the page handling code. I think, in terms of my code, it's a single thread per page but should be okay...
Rob Nicholson