7

Are the default objects supported by My keyword in VB.net is a kind of singleton? If not, what is the difference?

Again is this "default object" feature is something useful? If yes, then why it is not implemented in other languages like C#?

Gulshan
  • 9,532

2 Answers2

9

It is not a Singleton.

My is just a namespace containing static classes, methods and properties that point to other parts of the .NET framework, and provide some additional capabilities (e.g. CopyDirectory) Think of it as a set of shortcuts, a speed-dial of sorts.

Visual Basic provides language/compiler support with the My keyword. You can use the My classes in C# by adding a reference to Microsoft.VisualBasic.dll, but it is awkward, and not all classes are compatible with C# (they are VB specific). In C#, unless you want some of the VB capabilities (like "CopyDirectory"), it is more convenient to just reference the .NET framework classes directly, IMO.

Visual Basic has a somewhat different language philosophy than C# does. Originally, VB was to be the "applications" language, and C# was to be the "systems" language. Since then, the two languages have converged, and the feature sets of the two are almost indistinguishable, with a few notable differences (this being one, XML Literals being another).

I am quite certain that, if you asked Eric Lippert or one of the other members of the C# compiler team, they would tell you that implementing new features is a tug-of-war between available resources and feature importance, and that this particular feature just never hit threshold.

Navigate The .NET Framework And Your Projects With The My Namespace
http://msdn.microsoft.com/en-us/magazine/cc163680.aspx

My Namespace
http://msdn.microsoft.com/en-us/vbasic/ms789188

Robert Harvey
  • 200,592
0

My is a namespace not a singleton, but the "default objects supported by My keyword" are thread-local singletons (i.e. one instance per thread) as can be seen when using Reflector.

And the ThreadSafeObjectProvider<T> that provides this support is generated in each assembly compiled by VB.NET and is Friend so it is not available for external use.

Nevertheless its implementation is easy to replicate in your own ThreadSafeSinglton<T>. It is effectively a normal .NET singleton pattern except the backing field has the <ThreadStatic> attribute.

Mark Hurd
  • 343