Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

My and Microsoft.VisualBasic namespaces

2009-09-27

I never use the Microsoft.VisualBasic namespace, and I don’t think that it is there for other purposes than backwards compatibility with Visual Basic 6, with the possible exception of flirting with people who think this (C#)…

Interaction.MsgBox(Strings.Mid("Hello", 2, 2),MsgBoxStyle.OkOnly,"Extract [el]");

…for some reason makes more sense than this:

MessageBox.Show("Hello".Substring(1, 2), "Extract [el]");

The Microsoft.VisualBasic namespace is a part of the .NET Framework, but perhaps not your main focus if you don’t have some old converted VB6 code that you are managing. The My namespace however, is made me throw away parts of my own code libraries, because the My namespace gives you functions to call in your application that does common tasks, like uploading a file or playing a sound. The My namespace is only available in Visual Basic, as apposed to the Microsoft.VisualBasic namespace that can be used from any .NET language.

Extending the My namespace

Like any namespace in your application (and your application is where My belongs), just encapsulate your class in a namespace with the same name as you want to append your class to. This code adds Class1 to the My namespace (vb.net).

Namespace My
   Public Class Class1

   End Class
End Namespace

But what if you want to extend the existing classes, like My.Computer, with new functions? If you add a new class called Computer in the My namespace, you are actually shadowing the existing Computer class, making it unavailable. But there is a compiler trick here. Add a class called MyComputer to the My namespace. The prefix My of the class name, tells the compiler that you are extending the My.Computer class. Also, set the access level of the MyComputer class to Friend, like so:

Namespace My
   Friend Class MyComputer
      Public Sub Hello()

      End Sub
   End Class
End Namespace

Now, the Hello method is added to the My.Computer class.

If you like, you can create hidden modules instead of classes when you are extending the My namespace.

Categories: Visual Basic 9

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips