They both achieve the same thing. You cannot set data in the property. I'll assume it does it internally with the Read-only attribute as opposed to making the Set Private or one doesn't have the Set in the property. Either way you want to do it, it's a read-only property.
ReadOnly properties in Vb.Net
Hi,
What is the difference between a property declared as ReadOnly and a property that has a public Get method but a private SET method? Are these two things not equivalent? If they are, then why do we have two ways of doing the same thing?
Regards,
Sougata Ghosh
1 additional answer
Sort by: Most helpful
-
Peter Fleischer (former MVP) 19,231 Reputation points
2021-04-23T17:19:14.21+00:00 Hi,
there are differences.A value for the read-only property that you can set only once during instantiation (constructor or direct assignment to the property).
A value of the property with a private setter that you can set at any time during execution, but only within the class (object).
Try following console demo:
Module Module75 Sub Main() Try Dim c As New Demo c.Execute() Catch ex As Exception Console.WriteLine(ex.ToString) End Try Console.WriteLine("Continue enter key") Console.ReadKey() End Sub Friend Class Demo Friend Sub Execute() Try Dim c As New DemoProp("Prop 1") c.SetPropValue("Prop 3") Console.WriteLine(c.ROProp1) Console.WriteLine(c.ROProp2) Console.WriteLine(c.PrivateSetterProp) Catch ex As Exception Console.WriteLine(ex.Message) End Try End Sub End Class ''' <summary> ''' Demo class with different properties ''' </summary> Public Class DemoProp ''' <summary> ''' Constructor ''' </summary> ''' <param name="parameter">value to initial set readonly property</param> Public Sub New(parameter As String) ROProp1 = parameter End Sub ''' <summary> ''' readonly property with value from constructor ''' </summary> ''' <returns>value assigned in constructor</returns> Public ReadOnly Property ROProp1 As String ''' <summary> ''' readonly property with assigned value ''' </summary> ''' <returns>assigned value during instantiation</returns> Public ReadOnly Property ROProp2 As String = "Prop 2" ''' <summary> ''' backing field ''' </summary> Private _privatesetterProp As String ''' <summary> ''' property with private setter ''' </summary> ''' <returns>backing field</returns> Public Property PrivateSetterProp As String Get Return Me._privatesetterProp End Get Private Set(value As String) Me._privatesetterProp = value End Set End Property ''' <summary> ''' method to use property with private setter ''' </summary> ''' <param name="parameter">value to use private setter</param> Public Sub SetPropValue(parameter As String) PrivateSetterProp = parameter End Sub End Class End Module