Pass arguments to the property getter

5

VB.NET allows you to declare parameters in the property getter

Public ReadOnly Property Propriedade(param As String) As String
  Get
     Return param & "!"
  End Get
End Property

It's a strange feature and in C # it does not work. What is the practical use?

And why use properties with parameters instead of functions, such as:

Public Function GetFoo(param As String) As String
    Return param & "!"
End Function
    
asked by anonymous 26.10.2017 / 20:04

1 answer

5

There is in C # yes. They are Indexing Properties . And therefore they serve just to have an indicator of what the index of a collection of data is wanting to catch. It is possible to have more than one parameter, but all should be indexes of an array.

In VB.NET it's a bit more flexible because you can name the property and C # does not, so it's possible to have more than one indexer. But they should not be used as normal properties. If you have to pass argument to the getter , it is not a getter . VB.NET has questionable decisions.

It can be used with the setter also that would end up having at least two parameters.

Obviously this can be abused and used in the way shown in the question, but it is not recommended, it is outside the semantics for what was created. It should only have a property like this if the type being created is a collection of data.

Note that in VB.NET access to collections is done with parentheses equal to functions and gives the wrong impression that you are calling a method. In C # there is this confusion:

propriedade[indice]
propriedade[indice] = 1;

So as in VB.NET it is possible to abuse in C #:

public int this[int index] {
    get => 42 + index;
    set => WriteLine($"abusei {index}");
}

In C # it is possible to name the indexer for other languages that work with names see this name:

[System.Runtime.CompilerServices.IndexerName("NomeDoIndexador")]

But you can not have more than one. The default name is Item . I already replied because properties are often better than methods in certain scenarios .

    
26.10.2017 / 20:49