Beginners Guide to Functions

In this tutorial we are going to discuss the differences between subroutines and functions in both VB.Net and C#.Net. These are both considered ‘methods’ in the .Net world.

The basic difference between the two, is that a function returns some sort of data, but a subroutine does not. In other words, when we say ‘returns data’, the data could be a string, an integer, a DataSet, a DataReader or many other objects in the .Net world. The SubRoutine (or Sub) does not.

These two items (Subroutines and Functions) are some of the basic blocks of reuse when it comes to programming in .Net.

First, let’s look at Functions. and we’ll use a DataSet as an example. Inside your application, you might have many places in which you need a Dataset. There’s no reason to write the code over and over, so you’d create a method (in this case a Function) to return a Dataset.

In VB.Net, the signature would be something like this:

			Private Function CreateDataSet() As DataSet
			' your programming goes here
			End Function

In C#, the signature would be something like this:

			private DataSet CreateDataSet()
			{
			// your programming goes here
			}

In each case, ‘CreateDataSet’ is the name of the function. In VB.Net, adding ‘As DataSet’ at the end shows that you are wanting to create a DataSet and return it to the program. In C#, ‘DataSet’ is included in the initial signature, showing that you are, indeed, wanting to return a DataSet to the program.

You probably noticed the parentheses, just after ‘ CreateDataSet’. This is where you will put any arguments/parameters affecting the Function. Your particular needs will dictate which arguments or how many arguments you’ll need to fulfill the needs of your Function. Think of the arguments as being the items that might change from usage to usage throughout your program. They basically are variables, but instead of your normal declaration, they are included in the arguments of the Function.

For instance, if every place in your code used the same database table, and the only thing that needs to be different is your sql statement, then, you can include one argument (a string) which will be your sql statement.

In VB.Net, the signature would be something like this:
Continues…