VB.Net Properties - Public Get, Private Set

I decided that I would ask ... but is there a way to get part of the available Get property as public, but keep it private?

Otherwise, I think I need two properties or a property and a method, I just thought it would be cleaner.

+60
scope properties
Sep 22 '09 at 21:19
source share
6 answers

Yes, pretty 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 
+105
Sep 22 '09 at 21:21
source share

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 modified privately using _Name

+18
Mar 24 '16 at 8:44
source share
  Public Property Name() As String Get Return _name End Get Private Set(ByVal value As String) _name = value End Set End Property 
+7
Sep 22 '09 at 21:25
source share

One additional question worth mentioning: I'm not sure if this is a feature of .NET 4.0 or Visual Studio 2010, but if you use both, you do not need to declare a parameter value for the setter / mutator block of the code:

 Private _name As String Public Property Name() As String Get Return _name End Get Private Set _name = value End Set End Property 
+6
Apr 17 2018-12-12T00:
source share

I find marking property as readonly cleaner than the answers above. I believe vb14 is required.

 Private _Name As String Public ReadOnly Property Name() As String Get Return _Name End Get End Property 

It can be reduced to

 Public ReadOnly Property Name As String 

https://msdn.microsoft.com/en-us/library/dd293589.aspx?f=255&MSPPError=-2147217396

+4
Dec 07 '15 at 17:15
source share

If you are using VS2010 or newer, this is even easier than

 Public Property Name as String 

You get private properties and Get / Set is completely free!

see this blog post: Scott Hooke Blog

-four
Jun 17 '14 at 8:26
source share



All Articles