This is the second (and last) article on the My namespace. Last month, I showed you what is the My namespace and how to use it. This month, I will show you how to extend it with your own methods. As you will soon discover, it is as simple as adding 2 lines to a class that you might already have written.
Why extend this class?
You surely built many helper functions over the years. Most of those functions are probably declared as static so that you don’t have to create an instance of the class to use them.
The good news is that the My namespace can be extended so that your own classes can sit beside My.Application, My.Computer, My.User and so on.
My.Company
Imagine that you have a class that loads your company information (name, address, …) and that has everything needed to calculates taxes on invoice. That will be my scenario to show you how to extend the My namespace.
Create a Company class
You first need to create a class and name it Company. After you class has been created, surround the class definition with “Namespace My” and “End Namespace” so that your code looks like this:
Namespace My Public Class Company End Class End Namespace
Figure 1: My.Company in Intellisense
Adding members to your class
Now that your class has been created, you need to fill it with something useful.
Public Shared ReadOnly Property Name() As String Get Return "My company name" End Get End Property
Sub-classes are supported as well
Instead of adding all the properties and the methods relevant to the company but that may be indirectly, you could create sub-classes.
For example, you may want the calculations of taxes (for your invoices) to be done somewhere in the My.Company but would like to be clear to the user. The solution is to create a tax class inside the Company class.
You don’t need to do anything special to achieve this feature. Simply create another class inside the Company class. If you download my demo application, you will find the Tax class.
Extending My.Computer
If you would like to extend an existing class like the My.Computer class, it is possible but you need to follow some rules that may not be as straightforward as it was to expose your own class but at least you can do it!
Here is an example of code that adds a new method to the My.Computer class:
Namespace My Partial Friend Class MyComputer Public Sub MyMethod() MessageBox.Show("Hello, from My.Computer!!!") End Sub End Class End Namespace
Using this technique, you can also extend other classes like My.Application.
Conclusion
The My Namespace is very useful. Extending it is very easy. Be very careful not to clutter it.
I hope you appreciated the topic and see you next month.