Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.net Shared vs C# Static accessibility differences, why?

Tags:

c#

vb.net

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.

like image 868
dfasdljkhfaskldjhfasklhf Avatar asked Feb 04 '09 14:02

dfasdljkhfaskldjhfasklhf


2 Answers

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!

like image 82
Jon Skeet Avatar answered Nov 20 '22 19:11

Jon Skeet


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.

like image 23
Konrad Rudolph Avatar answered Nov 20 '22 18:11

Konrad Rudolph