Monday, March 1, 2021

Simplifying use of Static

Hope everyone must have come across static keyword while doing development, specifically using C#. Static modifier is used to declare static member, which means it belong to the type itself. Well, as part of this article, I’m not going to discuss more about static, but if you are interested in knowing more about it, here is the good reference. 

  1. public class Logger  
  2. {  
  3.      public static int GetLogLevel(string logType)  
  4.     {  
  5.          …  
  6.     }  
  7. } 

Above is a sample code snippet wherein, we have a class called Logger and it has a static method called GetLogLevel.

Now in order to call this GetLogLevel(…) method, first we have to add the required namespace, where this Logger class has been defined. Something like this,

  1. using Planner.Utilities;  

Well, nothing new as of now. Next, let’s have a look at, how to make a call to this static method.

  1. int logLevel = Logger.GetLogLevel(fileLog);  

Till here, nothing that bad, but we do have a room to improve our code by making it more readable and cleaner. Let’s re-write our code in below two steps:

Step 1: Using static keyword along with namespace

  1. using static Planner.Utilities.Logger;  

Step 2: Remove class name while calling static method

As we have already referred our class along with namespace, we need not to write that again. Hence, we can directly call our static method as shown below:

  1. int logLevel =GetLogLevel(fileLog);  

What do you think about this approach? Isn’t it cool?

1 comment: