Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hi guys, ive been working on a project latly (im a n00b to .net) and im wondering.. what is the difference between a function and a sub... from what i can tell, a function is something that gets something and returns a value, and a sub is what does something.. could someone explain to me what is what and when to use each one?

 

 

Thanks, Dan

Posted

Pretty much the only difference between the two is that a function returns a value. The last line of a function tells what value it will return, like this:

 

Return WhateverValueYouWant

Since a function returns a value, you will call it on the right side of an equals sign. That way you can assign the return value of the function to a variable. A sub procedure, however, is called by itself on its own line of code. It doesn't return a value, but just executes the code inside of it.

 

I hope this helps.

Take a look at my programs. Go to my web site.
Posted

You also usually declare a Function as a specific data type and Functions are normally passed some data or value to use in its process.

Public Function MyFunction(ByVal i As Integer, ByVal x As Long) As Long
    Dim n As Long
    'Some code here to do something...
    n = x * i
    Return n
End Function

Subs aren't type specific and don't always have data passed to them, although they can recieve some kind of data as a parameter. I like the way that the C languages deal with routines. ALL routines in the C's have a return type. If the routine is not required to return a value it is "void", other wise there is a data type associated with it. But, I digress. I know it's a lot more than you were asking but, for some reason I'm feeling long-winded tonight! Hope I did help a little.

Being smarter than you look is always better than looking smarter than you are.
  • *Experts*
Posted

EDIT: is it bad coding practice to have a function that doesnt return anything?

That will cause a compiler error if you have Option Strict On, which you should have.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...