11

NOTE: This is not a duplicate of VB.NET equivalent of C# property shorthand?. This question is about how to have different access rights on getter and setter of a VB auto-property; e.g public getter and private setter. That question is about the syntax for auto-property (and does not mention this issue).


I am trying to convert an auto Property (public getter and private setter) from C# to VB.NET.

But after conversion VB.NET is maintaining a private field.

C# code

class DemoViewModel
{
    DemoViewModel (){  AddCommand = new RelayCommand(); }

    public ICommand AddCommand {get;private set;}
}

VB.NET equivalent from code converter is

Class DemoViewModel
Private Sub New()
    AddCommand = New RelayCommand()
End Sub

Public Property AddCommand() As ICommand
    Get
        Return m_AddCommand
    End Get
    Private Set
        m_AddCommand = Value
    End Set
End Property
Private m_AddCommand As ICommand
End Class

VB.NET code generates private backing field.

Is it possible to get rid of this back field in source code (like c#)? How?

Without this feature, VB.NET source will have lots of such redundancy.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Tilak
  • 30,108
  • 19
  • 83
  • 131

3 Answers3

14

Using VB.NET, if you want to specify different accessibility for the Get and Set procedure, then you cannot use an auto-implemented property and must instead use standard, or expanded, property syntax.

Read MSDN: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/auto-implemented-properties


If getter and setter have same accessibility, e.g. both are Public, then you can use the auto-property syntax, e.g.:

Public Property Prop2 As String = "Empty"
Walkman
  • 67
  • 1
  • 2
  • 8
SergeyS
  • 3,515
  • 18
  • 27
  • 1
    Note: in MSDN link, the section that says can't use auto-property syntax in this case, is "Property Definitions That Require Standard Syntax", specifically "Specify different accessibility for the Get and Set procedure. For example, you might want to make the Set procedure Private and the Get procedure Public." – ToolmakerSteve Jan 24 '18 at 15:22
12

In VB.NET it's

Public ReadOnly Property Value As String

Then to access the private setter, you use an underscore before your property name

Me._Value = "Fred"
p3tch
  • 1,414
  • 13
  • 29
-1

since the answer(s) above hold(s), you may introduce a Public Prop to expose the Private one. This may not be a nice solution but still less code, than expanded Property syntax

Private Property internalprop as object
Public Readonly Property exposedprop as Object = internalprop
dba
  • 1,159
  • 1
  • 14
  • 22