1

Possible Duplicate:
When to Use Static Classes in C#

sorry if the question is meaningless or stupid am trying to create a windows service in which i have few class files each class file has some functions that calls another class file.

For example

class file one has a method to create email like

public bool CreateEmail()
{
 try
 {
 //code here
 }
 catch (Exception ex)
 {
    //Write to Log
    to create log  call function from **another class file**
 }
}

and many more calls like this.I would like to know if Using static class is better or creating object for each class and calling the methods will be better.Which is the recommended way?

Community
  • 1
  • 1
Karthik
  • 2,391
  • 6
  • 34
  • 65
  • 4
    You should have a look at this question: [When to Use Static Classes in C#](http://stackoverflow.com/questions/241339/when-to-use-static-classes-in-c-sharp) – Yannick Blondeau Oct 29 '12 at 07:41

4 Answers4

3

Think about:

  1. Do you need to do unit test, if yes, static class is not good and cannot be mocked in case you follow design for test ability.

  2. Single responsibility principle, don't put every method into one so-called utility class. Group methods in separate classes which are relevant together and follow SRP.

  3. Classes should have meaningful names. Utility, util or helper are not meaningful names

cuongle
  • 74,024
  • 28
  • 151
  • 206
3

Ask yourself

  • How relevant is this method to your object.
  • Does it alter the state of your object in anyway.

If its relevant and does change your object state ,then you should have the method inside the class.If not then you dont need to have that method in your class

In your case from the look of it,its quite clear that its not going to alter any state,rather it needs some information from the other object to send the mail.So i would definitely make this a util class(static class) and use it whenever i need.

Prabhu Murthy
  • 9,031
  • 5
  • 29
  • 36
2

If you are only using the class files to group the methods, and wont be needing instances of the class for anything other than calling those methods, then you should use a static class - thats what they are for.

Jeff
  • 12,085
  • 12
  • 82
  • 152
2

I would like to know if Using static class is better or creating object for each class and calling the methods will be better.

If it is a multi-threaded environment and logging requires some data to be shared across multiple calls, Create separate instance for each call. otherwise, go for static class and methods.

Azodious
  • 13,752
  • 1
  • 36
  • 71