Being a developer is all about making decisions and in the context of this Chess Club project, here's a decision that needs to be made. As part of the working application, you need to know the age of club members. Perhaps the club will have different levels of membership with different fees depending on the level – Juniors, Seniors, Veterans, and so on.
One choice you can make here is to decide is whether it would be better to use a property or a method in your class. As the class designer, you could choose to include an Age property. This would enable you to persist this data, but there is a potential danger. Age, by definition changes every day (and seemingly changes faster, the older you get!). So if you were to store a record of each instance’s age value, you'd need to build in a mechanism for checking regularly that someone hasn’t aged a year since the last time you checked, otherwise your data will be incorrect, and they'd be in the wrong category.
If you decided to create an Age property, then you have a further decision: will this be a property of the Person class, the ClubMember class or both?
On the other hand, if you decide to create a method that calculates the age dynamically, again you need to decide the most useful and logical place to have it.
Your final decision will depend a great deal on your assessment of how your class will be used. The fact is that in many cases there simply isn’t one sure-fire correct answer.
A Shared Method
In earlier articles in this series, you've seen how to create properties and methods. In the case of methods, this was the ToString method of the Person class. This was an Overridden method, overriding the method in the System.Object parent class. So you already have enough knowledge to select and implement any of those choices mentioned above.
In this article, simply because it adds another element to your skill set, I'm going to take a slightly different route. We'll create a new method, but will make it a Shared method.
Here’s one way of thinking about Shared methods. Ask yourself this question: Is it really necessary to create a whole new instance of the Person class or the ClubMember class in order to calculate an age?
If the answer to this question is no, then you may find that creating a Shared method to calculate an age will meet your needs perfectly.
The key point to note about a Shared method is that it isn’t necessary to call it via an instance of the class. In other words, if the Person class has a method named CalculateAge then it isn’t necessary to write this kind of code:
You don't need to create an instance of the Person class in order to access the CalculateAge method, because the method is Shared.
You'll have already used Shared methods in your projects. For example, if you've ever sorted an array with:
Array.Sort(MyArray)
or you've deleted a file with:
File.Delete(
"C:\Data\OldFile.txt")
then you've used a shared method.