Jake Freelander
Jake Freelander

Reputation: 1471

Shorthand for VB.net class constructors

I tend to make a bunch of POD classes for holding various data and they usually look like this:

Public class vertex
    public x as single
    public y as single
    Public sub New(x as single, y as single)
        Me.x = x
        Me.y = y
    End Sub
End class

Is there any way to not have to write out me.class_variable_name = function_variable_with_same_name? or some shorter way to do it?

Might seem like a pointless question but i tend to make those kinds of classes all the time and it just feels so reduntant writing the same variable names over and over again.

Upvotes: 0

Views: 1021

Answers (2)

OneFineDay
OneFineDay

Reputation: 9024

What's wrong with a constructor? Plus you can narrow the scope of the variables if you don't need or want to expose them.

Dim v As New vertext(2, 4)

Public class vertex
 Private x as single
 Private y as single
 Public sub New(x as single, y as single)
    Me.x = x
    Me.y = y
 End Sub
End class

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415705

You can use object initializers to skip the constructor entirely:

Public Class vertex
    Public Property x As Single
    Public Property y As Single
End Class


Dim v As New vertext() With {.x = 2, .y = 4}

Upvotes: 3

Related Questions