levis84
levis84

Reputation: 1054

VB.net class and function instance - most efficient method

I would like to know what you guys would do in this situation.

I am basically returning a data set for Person, but I would like to know the most efficient way of doing things.

Public Class TestClass
    Public Shared Function returnPersonData() As Person
        Dim p As New Person
        p.Address = "Here and there"
        p.Name = "Mike"
        p.Career = "Pilot"
        Return p
    End Function
End Class

Person class:

Public Class Person
    Public Property Name As String
    Public Property Address As String
    Public Property Career As String
End Class

I would then get the name by doing this in another class:

Dim name As String = TestClass.returnPersonData.Name
Dim address As String = TestClass.returnPersonData.Address

My question is this: why does it re-run the returnPersonData function every time I need to extract info the name, address and career? Why can't I just call the function once, save it in a data set, and then just reference that?

Upvotes: 0

Views: 62

Answers (1)

the_lotus
the_lotus

Reputation: 12748

Because you are calling it twice...

Dim name As String = TestClass.returnPersonData.Name ' <--- One time here
Dim address As String = TestClass.returnPersonData.Address ' <--- An other time here

Save the person class instance

Dim currentPerson As Person = TestClass.returnPersonData

Then you can get the name or address with

Dim name As String = currentPerson.Name
Dim address As String = currentPerson.Address

You could remove those two variables and just use currentPerson all the time.

Upvotes: 5

Related Questions