ReadOnly property or private set property that I should use in vb.net?

I like the automatic .NET properties, in C # it is so easy to declare a readonly property by declaring the set section as private as follows:

 public String Name{ get; private set; } 

But when I tried this in VB.NET, I was shocked that it is not supported, as mentioned here , and I have to write it like this:

 Private _Name as String Public ReadOnly Property Name as String Get return _Name End Get End Property 

Or:

 Private _Name as String Public Property Name as String Get return _Name End Get Private Set(value as String) _Name = value End Set End Property 

What is the difference between these ads in VB.NET , which one is preferable and why?

Edit

Which one will affect compile time, runtime, or performance?

+7
source share
3 answers

In the case of ReadOnly , only those who have access to the base variable can change the base value (for example, elements within the same class, for example) by directly applying such a change. In the latter case, the Private Set is almost the same thing - the elements within the class can change the base value, but they can do this using the property.

Which one is preferred is indirect: one of the advantages of the properties is that, like the method, you can have further implementation when applying the change (although side effects should be avoided, you can "check" and take exceptions, for example). If there is always something else when setting a value that is strongly related to setting a value, you can do it inside this set of properties, as opposed to having to code this implementation wherever you set .

+6
source

the first block will allow you to get the Name value. You cannot set Name.

the second block allows you to set the Name value from the class. Example:

 Me.Name = "new value" 

I would choose option 1, because the second option is verbose without providing any real meaning.

+1
source

The first declaration of the ReadOnly property makes it so that the property cannot be changed at all. The second Private Set allows you to change the property in the class in which you work in Me.Name = "str" .

In both cases, the base value can still be changed in the class using _Name = "str" .

0
source

All Articles