Q re Shared Methods

S

Simon Woods

Hi

I'm pretty new to vb.net and have a question because I'm not sure when to
use Shared as part of the method declaration. I understand, from my reading,
that this applies the method to the class rather than each object created
from that class, but I don't understand the applicability of this.

So for example, I have a business object working in the middle tier. I have
a collection class, MyBusinessObjects, which has a Function GetData and
returns a MyBusinessObject.

e.g.

Public Class MyBusinessObjects

Public Function GetData(KeyList() as String) as MyBusinessObject
....

or

Public Shared Function GetData(KeyList() as String) as
MyBusinessObject
...
End Class

So when I'm using this collection in my code, I could

Dim _MyBusinessObjects as New MyBusinessObjects
For Each _MyBusinessObject as MyBusinessObject in
_MyBusinessObjects.GetData(Keylist())
...
Next

or using the Shared declaration I could

For each _MyBusinessObject as MyBusinessObject in
MyBusinessObjects.GetData(Keylist())
...
Next

Perhaps my example isn't a very good one, but when should I use Shared and
when not?

Thanks

Simon
 
M

Mattias Sjögren

Perhaps my example isn't a very good one, but when should I use Shared and
when not?

You can use Shared whenever the method doesn't depend on any instance
data or method.


Mattias
 
P

Phill W.

Simon said:
I'm pretty new to vb.net and have a question because I'm not sure when to
use Shared as part of the method declaration. I understand, from my reading,
that this applies the method to the class rather than each object created
from that class, but I don't understand the applicability of this.

Consider the String class.

Dim s As String = "a,b,c,d,e"
Dim array() as String _
= s.Split( "," )

Here, you're using an Instance method (Split) that relies on the data
held in the /specific/ String object that it's called on.

s = String.Format( "{0},{1},{2}" _
array(0), array(1), array(2) )

This is using the Shared method, Format. Format doesn't operate on any
specific String, but it's "related" to other String-like operations so
the logical place to put it is in the String class.

HTH,
Phill W.
 
S

Simon Woods

Thanks Phill and Mattias
Consider the String class.

Dim s As String = "a,b,c,d,e"
Dim array() as String _
= s.Split( "," )

Here, you're using an Instance method (Split) that relies on the data
held in the /specific/ String object that it's called on.

s = String.Format( "{0},{1},{2}" _
array(0), array(1), array(2) )

This is using the Shared method, Format. Format doesn't operate on
any specific String, but it's "related" to other String-like
operations so the logical place to put it is in the String class.

HTH,
Phill W.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top