Code design:Static methods

by sunil ravulapalli /9. August 2010 16:24 /software-design /Comments (0)

Static methods are methods which belong to a class and not an instance of a class.

Normally, if you have a class like this:

public class Utility
{
 public string GetConnectionString()
 {
  return @"Data Source=.\SQLEXPRESS;AttachDbFilename=|***.mdf;Integrated Security=True;User Instance=True";
 }
}

you will use it like this:

Utility u = new Utility();
string conString = u.GetConnectionString();


But, lets say you want to use this all over your code and don't want to create an instance each time, you can redesign it like this:

public class Utility
{
 public static string GetConnectionString()
 {
  return @"Data Source=.\SQLEXPRESS;AttachDbFilename=***.mdf;Integrated Security=True;User Instance=True";
 }
}

you can just use it like this everywhere:

string conString = Utility.GetConnectionString();


Look, no instance!

blog comments powered by Disqus