Pass arguments to the property getter

Asked

Viewed 183 times

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 doesn’t 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

1 answer

6


Exists in C# yes. They are indexer properties. And so they serve precisely to have an indicator of what the content of a data collection is wanting to pick up. It is possible to have more than one parameter, but all should be indexes of a matrix.

In VB.NET it is a little more flexible because it can name the property and C# does not, so it is 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, he’s not a getter. VB.NET has questionable decisions.

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 such a property if the type being created is a data collection.

Note that in VB.NET the access to collections is done with parentheses equal to functions and gives a wrong impression that it is 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 working with names see this name:

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

I put in the Github for future reference.

But you still can’t have more than one. The default name is Item. I already answered because properties tend to be better than methods in certain scenarios.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.