.NET Tips and Tricks

Blog archive

Extend Your .NET Namespaces for Static Methods and Simpler Code

Let's say you've gone to the trouble of creating a CustomerRepository object with a static method called GetCustomerById. Something like this, in other words:

public class CustomerRepository
{
   public static Customer GetCustomerById(int Id)
   {

   }
}

In your file where you want to use that method you've added the appropriate using statement. Something like this, for example:

using SalesOrderMgmt.Repos;

And that's all great because now you can call your method straight from the class name, like this:

Customer cust = CustomerRepository.GetCustomerById(42);

But, because you're calling a static method, you can simplify your code a little more by extending your using statement down to the class level. Just add the keyword static to your using statement and end it with the class name. In other words, I'd rewrite my previous using statement to this:

using static SalesOrderMgmt.Repos.CustomerRepository;

Now I can use static method from my CustomerRepository class without referencing the class. My call to retrieve a customer object now looks like this:

Customer cust = GetCustomerById(42);

It also works with constants like PI in Math.PI. So go ahead and add this using statement to your code:

using static System.Math;

Now, when you calculate the area of a circle you can just write

double area = radius * PI^2;

Which I think is pretty cool. I can see how the resulting code might confuse the "next developer" who isn't familiar with this -- the next developer might reasonably expect GetCustomerById or PI to be declared in the class where I'm using it. But all that developer has to do is click on the method or constant name, press F12 and be taken straight to the actual code in the class where it's defined. If you're OK with extension methods, this isn't all that different.

Posted by Peter Vogel on 11/08/2019


comments powered by Disqus

Featured

Subscribe on YouTube