I am coming from the C# world to VB.NET and this puzzles me. Why are there 2 ways of doing the same thing? or is there some difference I am not aware of?
What is the difference between the following:
Public ReadOnly Property Test(ByVal v as String) As Integer
Public Function Test(ByVal v as String) As Integer
Functionally there is no difference, they both return a value based on a parameter. In fact, properties are actually transformed into functions during compilation, since the notion of a property doesn't exist in MSIL.
Semantically, however, there is a difference in how they should be used. Properties are meant as a way to expose the internal state of an object. Functions, on the other hand, are supposed to operate on an object's state to either provide an answer to a specific question (a query) or to modify the state in some way (a command).
Here's an example:
Public Class Rectangle Private _size As Size ReadOnly Property Size() As Size Get Return _size End Get End Property Public Function IsSquare() As Boolean Return _size.Width = _size.Height End Function End Class
Size simply exposes a property of the object, the
IsSquare function actually performs an operation on the object's internal state in order to answer a question.
Based on this principle, the most common use case for parameterized properties in VB.NET is in classes that represent a sequence of items, where the parameter is used to access a specific element in the sequence by its position or by some unique key. In other words, to create what's known as indexers in C#.