Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 4. Methods > Static Methods

Static Methods

A static method is a method that exists in a class as a whole, rather than in a specific instance of the class. As with other static members, the key benefit of static methods is that they reside apart from a particular instance of a class without polluting the application’s global space and without going against the object-oriented grain by not being associated with a class.

An example of a static member is a database API I wrote in C#. Within my class hierarchy, I had a class named SQLServerDb. Along with the basic new, update, read, and delete (NURD) capabilities, the class also contained a method to repair the database. In the class’s Repair method, I had no need to open the database itself. In fact, the open database connectivity (ODBC) function I used (SQLConfigDataSource) mandated that the database be closed for the operation. However, the SQLServerDb constructor opened a database specified in a database name passed to it. Therefore, a static method was perfect. The static method allowed me to place a method in the SQLServerDb class where it belonged, without going through my class’s constructor. Obviously, on the client side, the benefit was that the client didn’t have to instantiate the SQLServerDb class either. In the next example, you’ll see a static method (RepairDatabase) being called from within the Main method. Notice that we don’t create an instance of SQLServerDb to do this:


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint