Krzysztof Wurst
Krzysztof Wurst

Reputation: 9

Return two classes from VB.Net function

I am working on some tennis project and I need to return some data from a function. I created two classes:

Public Class Player
   Public Name As String
   Public Age As Integer
End Class

..and

Public Class tennisMatch
    Public Surface As String
    Public matchDate As Date
    Public Player1 As Player
    Public Player2 As Player
End Class

I want to have a function that returns an instance of tennisMatch so I can use it later, I tried this:

Public Function getMatch() As tennisMatch
    Dim Match As New tennisMatch

    Dim Player1 As New Player
    Player1.Name = "Steve"

    Match.Surface = "Clay"

    Return Match
End Function

Now, this works:

Console.WriteLine(getMatch.Surface)

However, this doesn't:

Console.WriteLine(getMatch.Player1.Name)

What am I doing wrong?

Upvotes: 0

Views: 250

Answers (1)

41686d6564
41686d6564

Reputation: 19641

You created the tennisMatch object, and the Player object, but you never added the Player you created to the created tennisMatch.

Try this:

Public Function getMatch() As tennisMatch
    Dim Match As New tennisMatch
    Match.Surface = "Clay"

    Dim Player1 As New Player
    Player1.Name = "Steve"
    Match.Player1 = Player1

    Return Match
End Function

The fact that you named the Player object "Player1" doesn't mean anything, you have to assign a value to the Player1 field of the tennisMatch class. The name of the variable doesn't matter. For example, the following should give you the same result as the previous code:

Dim somePlayer As New Player
somePlayer.Name = "Steve"
Match.Player1 = somePlayer

Moreover, in most cases, you should use Properties instead of fields for the public members of your classes. Check this question for more.

Hope that helps.

Upvotes: 2

Related Questions