Note: this is a continuity of the functions tutorial that you should read before proceeding.
Since we’ve already seen the constructors, the methods might seem a bit like more of the same. Things to remember:
1. A method always have a return value (except if it’s a Sub in Visual Basic);
2. It can have parameters if you want it to;
3. It can be overloaded;
4. It can override standard class methods;
5. A method should be named after an action, for example: Add, Execute, CalculatePower and so on;
6. A class can contain any number of methods but, frankly speaking, it shouldn’t be longer than about 1000 lines;
7. A method can have a scope, private, public of protected (we’re going to see the first two for now).
Creating a method should sound familiar if you followed the tutorial series, still I will give you a refresher!
Visual Basic
Option Explicit On Option Strict On Public Class Mouse 'Property short version Public Property Color As String Public Property NumberOfButtons As Integer Public Property LightsOn As Boolean 'Constructor Public Sub New() Color = "Black" NumberOfButtons = 3 LightsOn = False End Sub 'Method to turn the lights on Public Sub TurnLightsOn() LightsOn = True End Sub End Class
C#
namespace PropertiesCSharp { public class Mouse { public string Color { get; set; } public int NumberOfButtons { get; set; } public bool LightsOn { get; set; } public Mouse() { this.Color = "Black"; this.NumberOfButtons = 3; this.LightsOn = false; } public void TurnLightsOn() { LightsOn = true; } } }
This is the last tutorial example representing a computer mouse. As you can see I added a method called TurnLightsOn that returns no value, the purpose of that method is simply to turn the LEDs of the mouse on so it can illuminate (let’s say it’s a gaming mouse and looks cool).
Keep in mind that this method is an action that represents something you can accomplish in a real life scenario of clicking on a button to turn the lights on. We will often work with representation of real life objects in computer programming and any object you can think of can have properties and methods (actions).
Overload!
What is method overloading? Method overloading is the action of writing two methods with the same name but with a different signature (parameters).
Visual Basic
Option Explicit On Option Strict On Public Class Mouse 'Property short version Public Property Color As String Public Property NumberOfButtons As Integer Public Property LightsOn As Boolean 'Constructor Public Sub New() Color = "Black" NumberOfButtons = 3 LightsOn = False End Sub 'Method to turn the lights on Public Sub TurnLightsOn() LightsOn = True End Sub 'Same method name, but different signature, now it takes one parameter which indicates 'to the method to check if the lights are off first (just an example). Public Sub TurnLightsOn(Check As Boolean) If Check Then If (Not LightsOn) Then LightsOn = True End If Else TurnLightsOn() End If End Sub End Class
C#
namespace PropertiesCSharp { public class Mouse { public string Color { get; set; } public int NumberOfButtons { get; set; } public bool LightsOn { get; set; } public Mouse() { this.Color = "Black"; this.NumberOfButtons = 3; this.LightsOn = false; } public void TurnLightsOn() { LightsOn = true; } public void TurnLightsOn(bool Check) { //If the user wants to make a check if the lights are on if(Check) { if (!LightsOn) LightsOn = true; } else { //Else, simply turn the lights on as usual by calling the other method TurnLightsOn(); } } } }
I am still using a method that returns no value but I changed the parameters so that the compiler knows that I mean the same method but overloaded. If we try to call this method we will have the following result.
Visual Basic
C#
The preceding method has two overloads, the one without parameters and the one with one parameter of type Boolean, we could add more if we needed to!
Override!
Let’s add another method to our class which will be called ToString(), this method already exists by default and needs to be overridden. Overwrite is simply replacing the existing one by our creation. This will be more useful when inheriting classes but we’re not there yet! Let’s see out it works in action!
Visual Basic
'Override the ToString method Public Overrides Function ToString() As String Return MyBase.ToString() End Function
C#
//Override the ToString method public override string ToString() { return base.ToString(); }
I want to draw your attention on the Override keyword which will replace the method inherited, in this case by returning Base which represents the base class .ToString(). Most of the time it will return something like YourNamespace.ClassName. This is not a desired result, we would like something that describes the current state of the class better. You are the author of this class so you can choose what result you want returned. Here is what I will return in the ToString() method.
Visual Basic
'Override ToString Method Public Overrides Function ToString() As String Return "Color: " & Color & vbCrLf & "NumberOfButtons" & NumberOfButtons & vbCrLf & "LightsOn" & LightsOn End Function
C#
public override string ToString() { return "Color: " + Color + "\n" + "NumberOfButtons" + NumberOfButtons + "\n" + "LightsOn" + LightsOn; }
Want it or not, the ToString() method will be there but if you do not override it, it won’t serve any purpose most likely. Remember that it is used to provide a string representation of your class.
Here is the result of my ToString() method.
Visual Basic
C#
The Scope
The scope defines who will be able to access the different components, here we are still talking about the methods but they apply to properties and members as well.
Private
Private dictate that the method can only be accessed inside of the class (objet). It won’t be accessible by anything else, not even children of that class (we will see that later). It’s the most strict option.
Public
Public means that it’s going to be accessible by any code inside or outside of that class. It’s the less strict option.
A bit on Protected
Finally, protected is the same as private, except that it will also be available for use by the children of the current class.
Complete Code
Visual Basic – Mouse class
Option Explicit On Option Strict On Public Class Mouse 'Property short version Public Property Color As String Public Property NumberOfButtons As Integer Public Property LightsOn As Boolean 'Constructor Public Sub New() Color = "Black" NumberOfButtons = 3 LightsOn = False End Sub 'Method to turn the lights on Public Sub TurnLightsOn() LightsOn = True End Sub 'Same method name, but different signature, now it takes one parameter which indicates 'to the method to check if the lights are off first (just an example). Public Sub TurnLightsOn(Check As Boolean) If Check Then If (Not LightsOn) Then LightsOn = True End If Else TurnLightsOn() End If End Sub 'Override ToString Method Public Overrides Function ToString() As String Return "Color: " & Color & vbCrLf & "NumberOfButtons" & vbCrLf & "LightsOn" End Function End Class
C# – Mouse class
public class Mouse { public string Color { get; set; } public int NumberOfButtons { get; set; } public bool LightsOn { get; set; } public Mouse() { this.Color = "Black"; this.NumberOfButtons = 3; this.LightsOn = false; } public void TurnLightsOn() { LightsOn = true; } public void TurnLightsOn(bool Check) { //If the user wants to make a check if the lights are on if(Check) { if (!LightsOn) LightsOn = true; } else { //Else, simply turn the lights on as usual by calling the other method TurnLightsOn(); } } public override string ToString() { return "Color: " + Color + "\n" + "NumberOfButtons" + NumberOfButtons + "\n" + "LightsOn" + LightsOn; } }
What about the next tutorial?
Methods take an important part in classes. You need to use them to accomplish action and they can also help you divide a task that seems to take too many lines. Use them wisely!
In the next tutorial we’re going to have an exercice on classes in general which should give you a bit of practice on the subject!
For more information
Here are three links that might be of interest if you want to know even more about the subject, again, I am refering to our friends at Microsoft doing a great job at writing documentation!
1. Overload
2. Override
3. Scope
Keep in mind that these pages go into a lot more details than what we’ve just seen here, but I do think that what I’ve covered the essential of what you need to know.
Visual Basic
C#
No Comments Yet!
You can be first to comment this post!