Search code examples
.netmethodsfunctionshared

When to use Shared methods in .NET


I'm get kind of getting mixed messages about this so I'm hoping someone can clear this up for me.

Should I be using Shared methods/functions in the following situation:

I have a generic class named "Person". This class represents a person in the database.

I have a manager class named "PersonManager". This class contains methods which adds, updates, deletes individual Person objects. A method also exists to lookup Persons from the database.

Should these methods in the manager class be declared as shared methods? Or is it more appropriate to create a new instance of the PersonManager class each time and call the appropriate method on it.

So, if shared:

PersonManager.AddPerson(NewPerson)

versus non-shared:

Dim MyPersonManager as PersonManager
MyPersonManager.AddPerson(NewPerson)

When looking up Persons, the shared version would be:

Dim dt as New DataTable
dt = PersonManager.GetPersons

versus the non-shared version:

Dim dt as New DataTable
Dim MyPersonManager as New PersonManager
dt = MyPersonManager.GetPersons

Solution

  • Since shared methods and members are called static in C# there is already stuff on Stack Overflow...

    When to use static classes in C#