VB NET Object Oriented - vb.net

I'm a little new to classes on VB.NET (and to whole OOP concept in general) so sorry in advance for my poor explanation.
I've created a class like so:
Public Class MyApp
private var1 as integer = 2
Private Function getProfile(id As Integer)
'Imaginary server request according to ID
'Following that was received:
Dim name As String = "John"
Dim age As integer = 30
End Function
End Class
I want to be able to call getProfile by using myApp.getProfile and that's something I can handle.
What I can't manage is displaying only the age or name.
Something like this:
MyApp.getProfile(4341).age
How can I achieve something like this? Like having sub-functions in a function.

To call the method that way it needs to be static (marked Shared) and public. To make it return the name and age as properties you need a class with those properties. Example:
Public Class MyApp
Public Shared Function GetProfile(id As Integer)
Dim name As String = "John"
Dim age As integer = 30
return New ServerResult(name, age)
End Function
End Class
Public Class ServerResult
Public Name as String
Public Age as Integer
Public Sub New(n as String, a as Integer)
Name = n
age = a
End Sub
End Class
Usage example:
Dim age as Integer = MyApp.GetProfile(42).Age
Another:
Dim result As ServerResult = MyApp.GetProfile(1337)
Dim info As String = String.Format("{0}, {1}", result.Name, result.Age)
Note: Making the method static is based on how you wanted to call it. You might want to create an instance of the MyApp class instead, and have a method that is not static.

Related

Reference Variable names as strings

I am trying to reference the name of a variable as a string. I have a list of global variables
Public gvHeight As String = Blank
Public gvWeight As String = Blank
Public gvAge As String = Blank
I need to reference the name of the variables for an external API call. I am trying to avoid specific code per variable, instead allow me to add a new variable and everything reference correctly. I already have the rest of the code to deal with the name as a string.
example:
public Height as string
public weight as string
public age as string
[elsewhere in code]
for each var as string in {public variables}
CallToAPI(var.name) 'needs to send "height" "weight" or "age" but there are a lot so hardcoding is not a good solution
edited for example
You need to find the public fields through Reflection.
Having an example dll compiled from this source-code:
Public Class Class1
Public Field1 As String = "value 1"
Public Field2 As String = "value 2"
Public Field3 As Integer
End Class
Then you could do this:
' The library path.
Dim libpath As String = "...\ClassLibrary1.dll"
' The assembly.
Dim ass As Assembly = Assembly.LoadFile(libpath)
' The Class1 type. (full namespace is required)
Dim t As Type = ass.GetType("ClassLibrary1.Class1", throwOnError:=True)
' The public String fields in Class1.
Dim strFields As FieldInfo() =
(From f As FieldInfo In t.GetFields(BindingFlags.Instance Or BindingFlags.Public)
Where f.FieldType Is GetType(String)
).ToArray
' A simple iteration over the fields to print their names.
For Each field As FieldInfo In strFields
Console.WriteLine(field.Name)
Next strField
If all your variables are of the same type (here strings), you can use a Dictionary...
Public MyModule
Private myVars As Dictionary(Of String, String)
Public Function CallToAPI(VarName As String) As String
If myVars.ContainsKey(VarName) Then
Return myVars(VarName)
End If
Return ""
End Function
End Module
And somewhere else in your external code
Module TestModule
Public Sub Test()
Dim myVar = MyModule.CallToAPI("test")
End Sub
End Module
Now if your variables aren't the same, then you must use Reflection... and that's where the fun begins...

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?
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.

Naming global variables in a structured way

My current project has global constants that define certain rows and columns in workbooks that this project will be searching through. I have defined them as such:
Public Const headRow As Integer = 1
Public Const descRow As Integer = 2
Public Const pnumCol As Integer = 1
Public Const teamCol As Integer = 2
Public Const dateCol As Integer = 3
Public Const hourCol As Integer = 4
Public Const typeCol As Integer = 5
Public Const taskCol As Integer = 6
Public Const noteCol As Integer = 7
I'm wondering if there is a cleaner way to define these that would allow me to write these in a way such as:
ColumnNums.team
ColumnNums.task
ColumnNums.note 'etc
I think something similar to this could be done by defining my own type, but that would probably not be worthwhile. I'm basically wanting this to be an easy way to remember the variable names as I write more code, as well as to be able to count how many items I have in each group. Would a Type or Collection be useful in this case?
For mixed variable types, you can put it in a class module, name the class module ColumnNumbers and put the following code in:
Public Property Get Team() As Long
Team = 1
End Property
Public Property Get TeamName() As String
TeamName = "Team One! :-)"
End Property
Then you can use it in any module like this:
Dim colNums As New ColumnNumbers
Sub foo()
MsgBox colNums.Team
End Sub
If you only want to return long values, put it in an enum:
Enum ColumnNumbers
Team = 1
Description = 2
End Enum
Sub foo()
MsgBox ColumnNumbers.Team
End Sub
Chip pearson has already done a fantastic job of describing enums here it's worth a read if you have yet to discover them.
You could use public arrays like this:
Public ColumnNum(0 To 2) As Long
Public RowNum(0 To 2) As Long
Used together with an enum:
Public Enum Category
team
task
note 'etc.
End Enum
Then things like ColumnNum(team) will function like a public variable:
Sub test1()
ColumnNum(team) = 5
End Sub
Sub test2()
Debug.Print ColumnNum(team)
End Sub
If these two subs are run in order than 5 is printed.

Pass user input to new instance of class

Alright, I have looked through 20 pages on here and can't find what I'm looking for... I've seen it in C# and other languages.. but not Visual Basic..
Say I have a class:
Public Class Cars
Private doors as integer
Private Liters as double
Private otherStuff as string
' more code'
end class
Say I also have a Form.. an inputForm we'll call it that has numerous textboxes for users to input these characteristics. The first textbox is labeled nameTextBox. Is there any way to assign the string value of that textbox as a new car?
something to the likes of..
dim nameTextBox.value as new car
??
The fields in your class are private, so they arent of much use - no other code will be able to see those values.
Public Class Car
Public Property Make As String
Public Property Model As String
Public Property Year As Integer
' something the class may use/need but doesnt expose
Private DealerCost As Decimal
' the constructor - called when you create a NEW car
Public Sub New(mk As String, md As String)
Make = mk
Model = md
End Sub
...
End Class
By specifying only a constructor which takes params, I am saying that you cannot create a new car without specifying those properties. If the constructor takes no params, then you can create an "empty" car object and set each property individually. You can do both - called overloading - so you can create a car with or without the Make and Model at the outset.
As Public Properties, other code can examine them to see what kind of car this is.
Dim myCar = New Car("Toyata", "Corolla")
myCar.Year = 2013
myCar.Color = Color.Blue
The text used of course can come from user input:
Dim myCar = New Car(tbMake.Text, tbModel.Text)
Dim yr As Int32
If Integer.TryParse(tbYear.Text, yr) Then
myCar.Year = yr
Else
' ToDo: scold user
End If

Trying to make a class return a string

I'm moving code from code-behind to classes and run into a problem. I have a method which makes a string (an html invoice). In the method a final amount is created. I want to make a class called Invoice which will have the method "CreateInvoice" which will return a string and I also want to set the finalCharge property of the object. I have all the heavy lifting done but it's setting up the class is the part I'm having troubles with
Public Class Invoice
Public finalCharge As Double
Public invoiceString As String
Public billingId As Integer
Public clientID As Integer
Public Shared Function CreateInvoice(ByVal bill_id As Integer, ByVal client_id As Integer) As String
... 'create string invoice
... 'tally final charge
End Function
'On my code-behind page.
dim y as string
dim x as Invoice
y = x.CreateInvoice(1225,8855) <-- this line doesn't work.
Thank you for helping be get sorted out!
It's a Shared function - which means you don't need (or want) an instance of the class to use it. You should call it like:
Invoice.CreateInvoice(1225, 8855)
That said, I'm not entirely sure it should be Shared to begin with, since you also state:
[I]...want to set the finalCharge property
Since a Shared function can only access Shared properties (since there is no instance), you may really want it to be an instance function:
Public Class Invoice
Public finalCharge As Double
Public invoiceString As String
Public billingId As Integer
Public clientID As Integer
Public Function CreateInvoice(ByVal bill_id As Integer, ByVal client_id As Integer) As String
... 'create string invoice
Me.finalCharge = ... 'tally final charge
End Function
End Class
In which case, you'd call it like:
Dim x as New Invoice()
Dim y as String = x.CreateInvoice(1225, 8855)
Dim finalCharge as Double = x.finalCharge