Reputation: 18746
Public Class frmMain
Private p_dlgAdd As frmAdd = Nothing
Public ReadOnly Property _dlgAdd As frmAdd
Get
If p_dlgAdd Is Nothing Then
p_dlgAdd = New frmAdd()
End If
Return p_dlgAdd
End Get
End Property
Public Sub DoStuff()
''// Should not touch p_dlgAdd
End Sub
End Class
For a few types of objects I would prefer to initialize them only when needed (sql connection, mainframe connections, large forms), because some users only use very specific parts of the program (managers may use one mainframe to do what they want, regular users use another resource primarily).
Why the p_? I am thinking using p_ would help me not use or easily find in intellisense the variable instead of the property locally in that class. Then using _ alone in front of private properties or private variables that don't need to locally be accessed by a property.
What would be a good way to help prevent me from accidently accessing p_dlgAdd directly? Is this a good use for anonymous variables in 2008? (I don't have 2008 available at work yet, but they think we will have it soon)
Upvotes: 1
Views: 1515
Reputation: 4007
This is what Static is for.
Public Class frmMain
Public ReadOnly Property _dlgAdd As frmAdd
Get
Static dlgAdd As frmAdd = Nothing
If dlgAdd Is Nothing Then
dlgAdd = New frmAdd()
End If
Return dlgAdd
End Get
End Property
Public Sub DoStuff()
' cannot touch dlgAdd
End Sub
End Class
https://msdn.microsoft.com/en-us/library/z2cty7t8.aspx
Upvotes: 0
Reputation: 667
You can use the EditorBrowseableAttribute to hide a class member from Intellisense.
<EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> _
Private p_dlgAdd As frmAdd = Nothing
The other option that comes to mind is using a static analysis tool like Gendarme to check for violations of "don't access the field directly" rule. Not sure if Gendarme already has an appropriate rule, but it is extensible (may not be worth the effort in your case, however).
Upvotes: 2
Reputation: 3838
What you always CAN do (but it might be an overkill in your case), would be the Following:
public class Base
{
private frmAdd p_dlgAdd = null;
protected frmAdd _dlgAdd
{
get
{
if(p_dlgAdd == null)
p_dlgAdd = new frmAdd();
return p_dlgAdd;
}
}
}
In this way, your "p_dlgAdd" will not be accessible and _dlgAdd only in the derived class. But this only works if you can define/change the base type.
Upvotes: 0
Reputation: 12126
Honestly, I'm not familiar with anonymous variables. With that said, there is really no mechanism I know of to stop you from writing code to access a private variable from within the same class. Just pay attention to your code. If you want to put some sort of prefix on the variable to remind yourself, that is acceptable.
Upvotes: 0