Methods are used to for plenty of reasons:
- Cleaner code
- Code re-usability
- Easier maintenance
- Code readability
How does method actually look like?
Method consists of method signature and method body.
Method signature signature always look like this:
- Access modifier
- Return type or void
- Method name
- Parameters
1 |
public int MyIntMethod(int a, int b) |
And After method signature we have
- Opening curly brackets
- Method body/our logic
- Closing curly brackets
1 2 3 4 5 |
{ return a + b; } |
Let’s dissect this method:
1 2 3 4 5 6 7 8 |
public int MyIntMethod(int a, int b) { return a + b; } // this is a public method which has return type int, // is named MyIntMethod, has two int parameters // return value is addition of two parameters |
Our method could be void, meaning that method will not return any value.
1 2 3 4 5 6 7 8 9 |
public void MyVoidMethod(string a) { Console.WriteLine("This is my hello message"); } // this is a public method that returns no value, // is named MyVoidMethod, has one string parameter, // and outputs "This is my hello message" message // in console window |
Of course, our method can also be parameter-less, contain multiple parameters or with different access modifiers. We could also have multiple methods with same name but will have to have different parameters or at-least different order of same parameters.