Vb.Net Property Syntax

I asked my colleagues at work and even tried to find it on the Internet, but I could not get an answer.

What's the difference between

Public Property Name As String 

and

 Public Property Name() As String 

What difference does adding () after the property name make?

+6
source share
3 answers

First of all, you may find that a property has much in common with methods. from this putative bracket in the Property used for the parameters. if the property does not have a parameter, it can be omitted. The following is the complete syntax for declaring properties:

 [Default] [Modifiers] Property PropertyName[(ParameterList)] [As DataType] [AccessLevel] Get ' Statements of the Get procedure. ' The following statement returns an expression as the property value. Return Expression End Get [AccessLevel] Set[(ByVal NewValue As DataType)] ' Statements of the Set procedure. ' The following statement assigns newvalue as the property value. LValue = NewValue End Set End Property 

You can find valuable advice at the following links: What is the difference between a parameterized property and a function in vb.net? ALSO https://msdn.microsoft.com/en-us/library/e8ae41a4.aspx

+5
source

You are viewing these details in the VB.NET Language Specification . This is a fairly formal document, but nonetheless quite readable. Chapter 9.7 contains all syntax information for the Property keyword. For example, you will see:

 PropertySignature ::= Property Identifier [ OpenParenthesis [ ParameterList ] CloseParenthesis ] [ As [ Attributes ] TypeName ] 

The brackets [] indicate optional parts of the syntax. Thus, you can easily see that you do not need to use () if the property does not accept any parameters. In other words, if it is not an indexed property.

Therefore there is no difference.

+3
source

According to the online language link here , parentheses are required:

 Property name ( [ parameterlist ] ) 

although, as we know, they can be omitted without changing the value if there are no parameters.

However, when referencing a property, there is an important difference. If you have an overloaded property and overload with links to parameters, without which, parameters are required when invoking an overload without parameters, otherwise it is resolved as a call to self, which returns nothing.

That is, in the following code, line 17 displays the warning “uninitialized”: Return MyProp.ToUpper() , and it throws a null reference exception at run time.

If you add brackets to two “recursive” calls, that is, MyProp() , this will work as expected.

 Class Class1 Public Shared Sub Main() Dim c As New Class1 Console.WriteLine(c.MyProp(upper:=True)) End Sub Public Sub New() MyProp = "lower" End Sub Public ReadOnly Property MyProp As String Public ReadOnly Property MyProp(upper As Boolean) As String Get If upper Then Return MyProp.ToUpper() Else Return MyProp End If End Get End Property End Class 
0
source

All Articles