VB.Net Properties - Public Get, Private Set
vb.netPropertiesScopevb.net Problem Overview
I figured I would ask... but is there a way to have the Get part of a property available as public, but keep the set as private?
Otherwise I am thinking I need two properties or a property and a method, just figured this would be cleaner.
vb.net Solutions
Solution 1 - vb.net
Yes, quite straight forward:
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Private Set(ByVal value As String)
_name = value
End Set
End Property
Solution 2 - vb.net
I'm not sure what the minimum required version of Visual Studio is, but in VS2015 you can use
Public ReadOnly Property Name As String
It is read-only for public access but can be privately modified using _Name
Solution 3 - vb.net
Public Property Name() As String
Get
Return _name
End Get
Private Set(ByVal value As String)
_name = value
End Set
End Property
Solution 4 - vb.net
One additional tweak worth mentioning: I'm not sure if this is a .NET 4.0 or Visual Studio 2010 feature, but if you're using both you don't need to declare the value parameter for the setter/mutator block of code:
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Private Set
_name = value
End Set
End Property
Solution 5 - vb.net
I find marking the property
as readonly
cleaner than the above answers. I believe vb14 is required.
Private _Name As String
Public ReadOnly Property Name() As String
Get
Return _Name
End Get
End Property
This can be condensed to
Public ReadOnly Property Name As String
https://msdn.microsoft.com/en-us/library/dd293589.aspx?f=255&MSPPError=-2147217396
Solution 6 - vb.net
If you are using VS2010 or later it is even easier than that
Public Property Name as String
You get the private properties and Get/Set completely for free!
see this blog post: Scott Gu's Blog