newbie help with classes?

swu

Active member
Joined
Mar 26, 2005
Messages
33
Programming Experience
1-3
I need a really basic sample of how to call the same code from multiple declarations.

Basically I have some code that I would like to be ran when different things happen on a form. Currently I have cut and pasted the code throughout my program as a work around till I figure out how to "reuse" the code with in the program.

I think one option would be to create a class that could be called from multiple points in the program. Obviously there is a better solution than having the same code in multiple places.

if someone could show me a simple example of how to reuse code with in an app I think I could bang this one out.

Thanks in advance,

swu
 
You create a Function (if the code is to produce a result, or return some value) or a Procedure if it's just code that is executed. Where you would store the method is dependant upon where you will be using it. If you will only be using that code in one form, create the method in that form class. If you want to be able to call it from several forms, create it in either a seperate class or in a module. Of course there are other things that will come into question like whether to make the method shared, public, private, etc.

To create a Function:
VB.NET:
Public Function AddOne(ByVal i as Integer) as Integer
  Return i + 1
End Function

'to call it:
Dim int as Integer = AddOne(2) 'int will now have the value of 3
Notice the parameter (i); Functions are usually passed some value to work with then return some value.
To create a procedure:
VB.NET:
Private Sub ProcedureName()
  'the code to execute goes here
End Sub

'to call it simply:
ProcedureName()
 
Back
Top