Implications of "Public Shared" Sub / Function in VB

osdTech picture osdTech · Oct 20, 2012 · Viewed 26.7k times · Source

Can anyone explain me in VB i need to use Public Shared Sub so it can be accessed from another form.

But what this "Public" and "Shared" means?

  • Who is public?
  • With who is shared?

If it is public shared does this means some other software or "some hacker app" can easier have access to this sub and it's values?

Answer

dwerner picture dwerner · Oct 20, 2012

In VB.NET, Shared is equivalent to static in C# - meaning the member belongs to the class, not an instance of it. You might think that this member is 'Shared' among all instances, but this is not technically correct, even though VB.NET will resolve a Shared member though an instance invocation.

public class1
    public shared something as string
    public somethingelse as string
end class

The following code illustrates how VB.Net allows you to access these:

...
class1.something = "something" 'belongs to the class, no instance needed

dim x as new class1() with {.somethingelse = "something else"}

Console.WriteLine(x.somethingelse) 'prints "something else"

Console.Writeline(class1.something) 'prints "something" <- this is the correct way to access it

Console.Writeline(x.something) 'prints "something" but this is not recommended!
...

Public means any linking assembly can see and use this member.