0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, amazing!
Sorry for asking such a simple questions but I am self-learning and sometimes I have troubles ;)
That's totally fine. Glad I was able to help :)
In VS 2017 unless you need code in the get or set, you can just insert the word Property to get automatic properties. Public Property Surface As String This preserves the encapsulation principle of OOP as the compiler will create the get and set and the backer field.
@Mary That's for sure, but this isn't exclusively allowed in VS2017, it has always been the case at least since VS2010.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.