|
Thanks for another good article. I enjoy reading them. In this one you discuss the My* classes in the forthcoming VB.Net 2.0. You also ask why "this facility is not available in C#." As a matter of fact, they are. You can use them from any .Net language including non-Microsoft ones as well. Here are instructions to use it from C#:
1. Add a reference to Microsoft.VisualBasic.dll.
Note that this is always references for you in all VB projects which is why you need not reference it in VB.
(Optional)
2. To save yourself a little typing, add "using Microsoft.VisualBasic.MyServices;".
Note that these are the same instructions to use any other .Net DLL.
Here are a few examples from your article and equivalant C#:
'VB code
Me.cbNetworked.Checked = My.Computer.Network.IsAvailable
// C# code
MyComputer mc = new MyComputer();
cbNetworked.Checked = mc.Network.IsAvailable;
'VB code
Me.cbAltKey.Checked = My.Computer.Keyboard.AltKeyDown
Me.cbCapsLock.Checked = My.Computer.Keyboard.CapsLock
Me.cbCtrlKey.Checked = My.Computer.Keyboard.CtrlKeyDown
' etc...
// C# code
MyComputer mc = new MyComputer();
this.cbAltKey.Checked = mc.Computer.Keyboard.AltKeyDown;
this.cbCapsLock.Checked = mc.Computer.Keyboard.CapsLock;
this.cbCtrlKey.Checked = mc.Computer.Keyboard.CtrlKeyDown;
' etc...
'VB code
My.Computer.Audio.Play(lbClips.SelectedItem)
// C# code
MyAudio ma = new MyAudio();
ma.Play(lbClips.SelectedItem);
'VB code
My.Computer.Info.TotalPhysicalMemory
'etc...
// C# code
MyComputer mc = new MyComputer();
mc.Info.TotalPhysicalMemory;
// etc...
The list could go on and on, but I think I've made my point. If you look at the IL for most of these, they are just thin wrappers around other types in the standard framework. The main advantages that I see with the My* classes are these:
1. Simplified syntax. No need to create an instance of said object; can use as if it were static thanks to the compiler (which they really aren't).
2. Quick and easy location for related functionality. Some of the other methods are slightly harder to track down without looking at the IL. I don't think it would be to difficult to quickly create a table mapping each My* to the real .Net type. "Reflector" is a great tool to assist with that.
I don't see a need for a "My" keyword in C#. All of the functionality is already there for comsumption now. A new keyword would just bloat things and not add anything significant. If absolutlely necessary, one could just create a static wrapper class called "My" that would duplicate the same functionality.
|