Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the setter of a VB.NET property require a typed argument and why is it ByVal?

Tags:

c#

vb.net

In C#, a property's setter value keyword will automatically be same as the property's type.

For example, in C# ,type of value is string

private string str = string.Empty;
public string MyText 
{
    get { return str; }
    set { str = value; }
}

If we convert this snippet to VB.Net we get

Private str As String = String.Empty
Public Property MyText() As String
    Get
        Return str 
    End Get
    Set(ByVal value As String)
        str = value
    End Set
End Property

Questions

  1. Why does set have this line Set(ByVal value As String)? Shouldn't value type automatically be String. This way.

    Private str As String = String.Empty
    Public Property MyText() As String
        Get
            Return str 
        End Get
        Set
            str = value
        End Set
    End Property
    

    What's the use of that?

  2. I cannot change BYVal to ByRef (I tried, it gives error), then what's use of that also?

like image 286
Nikhil Agrawal Avatar asked Sep 12 '12 07:09

Nikhil Agrawal


1 Answers

You can omit the (ByVal value As String) part. Visual Studio will keep adding it, but it is not required by either the language nor the compiler.

You can use a parameter name other than value. Also note that since VS2010 SP1, you can omit the ByVal keyword.


Example:

Class Test

    Private str As String = String.Empty

    Public Property MyText() As String
        Get
            Return str 
        End Get
        Set
            str = value
        End Set
    End Property

    Public Property MyText2() As String
        Get
            Return str 
        End Get
        Set(something As String)
            str = something
        End Set
    End Property

End Class
like image 135
sloth Avatar answered Nov 10 '22 00:11

sloth