Keyword

# Sub

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Description

Declares the name, parameters, and code that form the body of a subroutine (method).

## Usage

For use in `XojoScript</api/language/xojo_script/xojoscript>` code:

``` xojo
Sub name [( parameterList )]
  [ local variable declarations ]
  [ statements ]
  [ Return ]
  [ statements ]
  [ exception handlers ]
  [ Finally ]
    [ statements ]
End [ Sub ]
```

| Part          | Description                                                                                                                                                                                                          |
|---------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| name          | The name of the subroutine (method); it follows standard variable naming conventions. You cannot use `Reserved Words</getting_started/using_the_xojo_language/reserved_words>` words in naming a method or function. |
| parameterList | Optional list of values representing parameters that are passed to the Subroutine when it is called. Multiple parameters are separated by commas.                                                                    |

## Notes

The <span class="title-ref">Sub</span> statement is used to define a method that does not return a value. Methods are usually associated with an object (exceptions are global methods or functions that are part of a module). All executable code must be in a <span class="title-ref">Sub</span> or `Function</api/language/function>` statement. A <span class="title-ref">Sub</span> cannot be defined inside another <span class="title-ref">Sub</span> or `Function</api/language/function>`. A <span class="title-ref">Sub</span> executes each line of code from the top down, assuming that you have not used the `GoTo</api/language/goto>` statement. Once the last line of code is executed, control returns to the line following the statement that called the <span class="title-ref">Sub</span>.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

### Declaring parameters

When you declare parameters, you declare the name of each parameter and its data type in the form:

``` xojo
ParameterName As DataType
```

If you declare more than one parameter, separate each declaration with a comma. You can optionally set a default value for the parameter using the syntax:

``` xojo
ParameterName As DataType = DefaultValue
```

For example, if you want to declare the parameter "StartValue" as an Integer and give it value of 1, you would write

``` xojo
StartValue As Integer = 1
```

You can provide default values for more than one parameter. For example, the following is valid:

``` xojo
a As Integer = 10, b As Integer = 20
```

When you pass a default value, you can use either a literal (as shown here), a `constant</api/language/const>`, or an `enum</api/data_types/enumeration>`. If you don't provide a default value, the parameter takes the default value for the data type, e.g., 0 for numbers, a null string ("") for strings.

You use the same syntax to use a constant as the default value. For example, suppose you define a global constant in a module, InitialValue. You can use it as a default value for a parameter like this:

``` xojo
a As Integer = InitialValue
```

Similarly, you can use an `enum</api/data_types/enumeration>` as a default value. Suppose you have created an `enum</api/data_types/enumeration>` in a module called SecurityLevel, with values None, Minimum, Maximum, and Forced. You can then assign the default value of a parameter using one of the enum values:

``` xojo
a As Integer = SecurityLevel.Forced
```

When a method is called, you have the option of passing a value to a parameter using the `assignment</api/language/equals>` operator. For example, you can pass the value of 10 to an `Integer</api/data_types/integer>` parameter of the method myMethod using the syntax:

``` xojo
myMethod = 10
```

You can also make a parameter optional. If you need to specify that one of the parameters in the method is optional without giving it a default value, use the `Optional</api/language/optional>` keyword. This modifier precedes the parameter name. An optional parameter does no take on a default value in the called method. If the caller omits this parameter, it will receive the standard default value for its data type.

When you pass a value to a method, you have the option of using the assignment operator. For example, you can pass the value of 10 to a method using the statement:

``` xojo
myMethod = 10
```

However, the assignment operator can be used only if you use the `Assigns</api/language/assigns>` keyword when you declare the method. For example, if the method "myMethod" takes one parameter and the Assigns keyword is used, the declaration would be:

``` xojo
Assigns StartValue As Integer
```

You could then call myMethod and provide the default value for StartValue with the statement:

``` xojo
myMethod = 10
```

You can use the `Assigns</api/language/assigns>` keyword with methods that take more than one parameter, but only the last parameter can use `Assigns</api/language/assigns>`. For example, the following declaration is valid:

``` xojo
a As Integer, b As Integer, Assigns c As Integer
```

With this declaration, the method can be called like this:

``` xojo
myMethod(5, 4) = 10
```

When you use the Assigns keyword, you cannot use the 'normal' syntax shown below:

``` xojo
myMethod(5, 4, 10) ' doesn't work with Assigns
```

An array can be passed as a parameter. To specify that a parameter is an array, place empty parentheses after the name of the array in the declaration. You can pass multi-dimensional arrays without specifying the number of elements in each dimension, but you need to indicate the number of dimensions. Do this by placing one fewer commas in the parentheses than dimensions.

See the `Function</api/language/function>` statement for more information.

By default, parameter passing is done by value and the value cannot be modified by the method. You can also pass a parameter by reference. When you pass a parameter by reference, a pointer to the object is passed. This allows you to return a value using the parameter.

If you want to pass a parameter by reference, precede it by the keyword `ByRef</api/language/byref>` in the parameter list, e.g., `ByRef</api/language/byref>` MyInt as `Integer</api/data_types/integer>`.

You call a <span class="title-ref">Sub</span> by using its name followed by any parameters in parentheses.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

### Variables

Variables used in a <span class="title-ref">Sub</span> can be global, public, protected, private, or local in scope. Global variables can be accessed from within any <span class="title-ref">Sub</span> or `Function</api/language/function>`. They exist from the moment the application runs to the time it quits. Global variables are created by creating properties of a module and declaring their scope Global. Public variables (a.k.a. properties) work like global properties except that the name of the owning window, class, or module must be used when referring to them, e.g., "module1.publicProperty". Private and protected properties are available only within the owning object and are called using the name of the owning window, class, or module.

Local variables are variables that are created each time the <span class="title-ref">Sub</span> is run and destroyed when the <span class="title-ref">Sub</span> finishes. Consequently, they can only be accessed by the statements within the <span class="title-ref">Sub</span>. They are created by using the `Var</api/language/var>` statement from within a <span class="title-ref">Sub</span> or `Function</api/language/function>`. A `Var</api/language/var>` statement can appear anywhere within the <span class="title-ref">Sub</span>.

The `Return</api/language/return>` statement can be used to immediately return control to the statement that called the <span class="title-ref">Sub</span>.

Exception handlers are statements that handle runtime errors. See the `RuntimeException</api/exceptions/runtimeexception>` class and the `` Exception</api/exceptions/exception>`and :doc:`Try</api/language/try> `` statements for more information.

Sometimes a method needs to do some cleanup work whether it is finishing normally or aborting early because of an exception. The optional `Finally</api/language/finally>` statement at the end of the method runs after the exception handlers, if it has any. Code in this block will be executed even if an exception has occured, whether the exception was handled or not.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

### Constants

The built-in metaconstant `CurrentMethodName</api/language/currentmethodname>` is available in all methods and events. It automatically contains the fully qualified name of the method or event. It is the same as if the user had declared the constant manually:

``` xojo
Const CurrentMethodName = "methodname"
```

For example, if you create a method, MyNewMethod, belonging to Window1 that has the code:

``` xojo
MessageBox(CurrentMethodName)
```

A call to this method will display the name "Window1.MyNewMethod".

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

### Functions

If you need your method to return a value, you will want to declare it as a `Function</api/language/function>`. A `Function</api/language/function>` is a method that can return a value. The value can be a one-dimensional array. A <span class="title-ref">Sub</span> method can call itself resulting in recursion. Too much recursion can lead to `StackOverFlowException</api/exceptions/stackoverflowexception>` errors.

## Compatibility

|                       |     |
|-----------------------|-----|
| **Project Types**     | All |
| **Operating Systems** | All |

<div class="seealso">

`Break</api/language/break>`, `Catch</api/language/catch>`, `Exit</api/language/loops/exit>`, `Finally</api/language/finally>`, `Function</api/language/function>`, `Return</api/language/return>` statements; `RuntimeException</api/exceptions/runtimeexception>` class; `Exception</api/exceptions/exception>`, `Try</api/language/try>` statements; `CurrentMethodName</api/language/currentmethodname>` constant.

</div>
