I see little functional difference between using a property
public readonly property foo as string get return bar end get end property
or a function
public function foo() as string return bar end function
Why would I want to use one form over the other?
Thanks!
The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be assigned multiple times in the field declaration and in any constructor. Therefore, readonly fields can have different values depending on the constructor used.
Code consuming a ReadOnly property cannot set its value. But code that has access to the underlying storage can assign or change the value at any time. You can assign a value to a ReadOnly variable only in its declaration or in the constructor of a class or structure in which it is defined.
The readonly means simply that no setter method was synthesized, and therefore using the dot notation to set a value fails with a compiler error. The dot notation fails because the compiler stops you from calling a method (the setter) that does not exist.
I read an interesting article recently in Visual Studio Magazine that discussed the different between Methods and Properties.
Properties are supposed to return a value and the same value each time unless something else is called in between.
A Method on the other hand is typically expected to do something in the background to get the value, or that the method may change the value each time it is called, like GetNextId() or something.
DateTime.Now is a good example of a Property that should have been a Method since it returns a different value each time it is used.
For those interested- here is the article
Choose Between Methods and Properties
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