tags:

views:

1245

answers:

3

This may be a dumb question - but why are shared methods availible on types and instances in VB.net - am I wrong to assume they are the equivalent to C# static methods?

i.e

MyClass.MySharedMethod()

dim mc as new MyClass()
mc.MySharedMethod()

Why am I allowed to do this? What possible advantage is there to this - all I can see this doing is confusing people when using intellisense. I'm sure this has to do with some convention from classic VB6 by why bother bring this up to .NET - it just seems so broken to me.

+1  A: 

This may be a dumb question - but why are shared methods availible on types and instances in VB.net - am I wrong to assume they are the equivalent to C# static methods?

They are the same. VB will warn if you try to use them on instances but it's not forbidden. This has probably got to do with dynamic typing and late binding. Imagine that you've got a late-bound object (Object) without knowing its exact type. How would you go about calling a static method of its class?

As far as I know, this wouldn't be possible in C# (without resorting to reflection). In VB with Option Strict Off, you could simply call it as an instance method of the object.

Konrad Rudolph
ok so why is it not forbidden then - they know its a bad idea if they warn you - so why bother?
BPAndrew
+11  A: 

Yes, it's basically a hangover from VB6. Java lets you do this too, but most IDEs warn you these days I believe.

And yes, it's a really bad idea. The most obvious example of it being bad is Thread.Sleep:

Dim t as new Thread(...)
t.Sleep(1000)

Which thread is sleeping? The current one. Doh!

Jon Skeet
Well, VB6 had no shared subs/functions in classes. How can this be a hangover?
Konrad Rudolph
love the example
JaredPar
@Konrad: Ooh, interesting. I'd heard (a while ago) that it was a backwards compatibility thing. Odd if it's not...
Jon Skeet
@Jon,Konrad, it seems even Paul doesn't know why this was allowed. If he doesn't know, the decision is likely lost in time for good. http://panopticoncentral.net/archive/2003/08/07/172.aspx
JaredPar
It turns out this was put into Vb.Net for ease of use. At least that's the concensus of the people remaining from the time this was designed.
JaredPar
+1  A: 

See "Accessing shared members from instances" by Paul Vick.

http://panopticoncentral.net/archive/2003/08/07/172.aspx

ggf31416