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.
An auto-implemented property is equivalent to a property for which the property value is stored in a private field. The following code example shows an auto-implemented property.
The generated getter/setter method will be public unless you explicitly specify an AccessLevel , as shown in the example below. Legal access levels are PUBLIC , PROTECTED , PACKAGE , and PRIVATE . You can also put a @Getter and/or @Setter annotation on a class.
Automatic property in C# is a property that has backing field generated by compiler. It saves developers from writing primitive getters and setters that just return value of backing field or assign to it. We can use attributes in many cases but often we need properties because features in different .
Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property. The get and set accessors for the same property may have different access modifiers.
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://docs.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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With