Tilak
Tilak

Reputation: 30698

Auto Property with public getter and private setter

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.

Upvotes: 14

Views: 9055

Answers (3)

SergeyS
SergeyS

Reputation: 3553

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"

Upvotes: 14

p3tch
p3tch

Reputation: 1495

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"

Upvotes: 17

dba
dba

Reputation: 1175

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

Upvotes: -1

Related Questions