Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implications of "Public Shared" Sub / Function in VB

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?

like image 981
osdTech Avatar asked Oct 20 '12 18:10

osdTech


2 Answers

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.

like image 97
dwerner Avatar answered Sep 22 '22 13:09

dwerner


The Public accessor keyword simply means that the method, property, etc. is visible and callable from outside of the DLL or Assembly that defined it.

The Shared keyword means that the method, etc. is not "instanced". That is, it is part of the Class definition only, and not part of the objects that are created ("instanced") from that Class definition. This has two principal effects:

  1. The Shared method can be called at anytime, without actually having an object/instance of that Class. and,
  2. Shared methods cannot access any of the non-Shared parts of the Class definition (unless an object instance is passed to it). They can only directly access the other Shared parts of the Class definition.
like image 35
RBarryYoung Avatar answered Sep 25 '22 13:09

RBarryYoung