Functions / Methods¶
A function
is a block of code that will run whenever we call it, think of our Main
function.
We usually use functions / methods to make our code easier to read, organized, reusable, etc.
In object-oriented programming, a method is simply a function that belongs to a class or object.
In C#, every function is technically a method, because all code must reside in a class.
Anatomy of a Function / Method¶
Component | Description | Example |
---|---|---|
Return Type | Data type returned after execution | int , void |
Name | Identifier used to call the function | Add , PrintLine |
Parameters | Input values used inside the function | (int a, int b) |
Body | Block of statements executed when called | { return a + b; } |
Example
Note
You might notice we have two PrintLine()
functions.
This is called function overloading—multiple functions can share the same name if their parameter lists or functions signature differs.
Calling
these functions would look something like this:
Example