Assume that you are working on an application that heavily relies on logging data to some desitnation.
If you are using log4net or application insights, you will create a separate class that does this for you.
Every time, request comes in to log something from your application, ideal way would be to create an object of this class as below and then call LogData method.
Instead of doing that, you can do something like below using static keywords (where you will not be creating an object of logger class everytime)
- public class Logger
- {
-
- public Logger()
- {
-
-
- }
- public void LogData(object[] data)
- {
-
- }
-
-
- }
-
- in your calling application code:
- Logger _logger = new Logger();
- Logger.LogData(array);
Using static keyword: making class static, you don't want any one else to create an object of this class and let this class only handle the way of logging. (like creating ILog objects and how it should log the data)
- public static class Logger
- {
-
-
- public static void LogData(object[] data)
- {
-
- }
- }
-
- in your calling application code:
- Logger.LogData(array);
Another example would be to open or close connection to SQL server or Oracle DB. Where you can easily make a call to methods to close or open the connection using class.MethodName.
Let's say your static class would make appropriate connection to either sql server db or oracle db based on the data you are providing to this method.
Instead of your calling class making decision what method to call (either sql logging or oracle logging), let logger class only decide what to do if data is of specific type.
So in all cases, you will end up making call to Logger.LogData() method and that class will handle the rest instead of you making call to Logger.LogSQL() or Logger.LogOracle().
When you define static class to make SQL connection, this class will control the behavior of how it should connect to sql server and what needs to be done in case of closing the connection.
So, when you don't want other parts of applications to control the behavior of certain functionality, you should put that in static class, doing thus, you are making sure that functionality won't be changed by other classes.