Static in C# - Part 2

Luke - Jun 24 - - Dev Community

In a previous article, I wrote about static definition, now we will go deeply - where, when and how to use it.

Where can use static?

We can use it in following items:

  • Variable
  • Field
  • Method
  • Function
  • Class
  • Constructor Take a look at the example below to get more info

Static function

static func

In the following picture, we can include some things:

  • With variable:
    • Global: require static type
    • Local: not require static type
  • It can be call by other function (static / non-static)
  • It can't call other non-static function

Static class

static class

When we apply static to class, everything of class (even the constructor), I repeat everything must be static

Static constructor

static constructor

Some things we can take notes on here:

  • Can use for both static / non-static class
  • Don't have parameter
  • Will be call when the class is accessed for the first time.
  • With non-static class, it can have both two types of constructor

Best Practise

In my opinion, I usually use static in two cases:

  • Utility (useful function I write for myself - ex: GetValueByKey, GetNameByStatus)
  • Extension method (extend function for specific class - ex: GetUserId)

Example - Utility

util func

Here is the utility function I use to get value in web.config, when I want get any value in config file, just call

use util

Example - Extension

Here are some extension method I wrote for ASP.NET Identity

extension method

For a short explanation, two methods above would return Access Level and Product Segment in User Claims. It can be used like build-in function for Identity

use extension

P/s: The pain point of static type is management. It declare one at run time and exists until the program finish, it can make exceptions if we don't manage access carefully. That's why Singleton pattern was born to cure it.

. . . . . . . . . . . . .