Function – Method in CSharp
In this lecture we are going to cover the basics of Functions / Methods. In CSharp they are basically the same.
“When a function is a part of a class, it’s called a method.
C# is an OOP language and doesn’t have functions that are declared outside of classes, that’s why all functions in C# are actually methods.
Though, beside this formal difference, they are the same…”
Why use Functions/Methods in CSharp?
Methods are required to run the piece of code which is inside the method. That sounds very basic but is very powerful. The beauty about this, is that there are tons of methods within the basic C# classes. That means we can use them with just a simple call.
How is a method structure:
access modifier + (static) + data type or void + method name + (parameter) + { // content of the method }
The access modifier can be the following:
- public (the method can be called from any class)
- private (the method can only be called from the class where it is declared)
- protected (the method can only be called from classes within the same tree)
All of those will make more sense as soon as we get to the object oriented part of the course. For now just use public for your methods.
Use the
static
modifier to declare a static member, which belongs to the type itself rather than to a specific object. Thestatic
modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes. For more information, see Static Classes and Static Class Members.
The “data type” part of the method is the data type that should be returned by the method when it is called. If the method should not return anything you can use the void term instead. In that case the method just runs the code within the body of the function without returning anything.
Call a Function/Method in CSharp
In order to call the function you just need to write it’s name and give it the required arguments. The arguments is what you give as parameters.
A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.
// declare method public int myCalc (int value1, int value2){ return value1+value2; } // call method myCalc(5,7) // will return the int value of 12
If you want to call a method that doesn’t have a return value than you can simply call the method this way:
methodName();
Now you know how to declare your own methods and how to call them. You can also call methods of classes which you have not created yourself, but more about that later in the series. We will look a bit more into Methods with Arguements in the next lecture.