Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static members in VB.NET

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.

like image 386
Rob Nicholson Avatar asked Jan 23 '23 04:01

Rob Nicholson


1 Answers

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.

like image 99
mmx Avatar answered Feb 03 '23 15:02

mmx