Home > Refactorings > Refactorings to convert between static and instance members

Refactorings to convert between static and instance members

October 31st, 2011

Classes allow you to create instance members and static members. Instance members are available when an instance of the class is created and have access to the object’s data. Static members do not require an object created and can be called directly.

Static methods are useful when creating functions that are not reliant on any instance of a class. An example of the extensive use of static members is the System.Math class, which is a library of mathematical functions and constants provided by the .NET framework.

If you declare instance fields, they are created and initialized when an instance of the class is created. Static fields apply only to the class itself. No matter how many instances of a class there are, there is only one instance of that classes’ static fields. In contrast, instance fields may have different instances and values for each class instance created. Theoretically, static members perform faster than instance members, because there is no need to create an instance of a class. However, the penalty for using instance methods is minor and should only be noticeable when calling billions or trillions of members. If the software that you are developing is performance critical, it may be worthwhile to convert some instance members to static members. But bear in mind, that may decrease the readability and maintainability of the code.

To help you easily convert static members into instance members and vice versa, Refactor! Pro provides two refactorings:

  • Make Member Static
  • Make Member Non-static

The first one allows you to convert an instance member that can be made static into a static one. An instance member should not reference any other instance members to be static. The refactoring not only adds a static keyword (‘Shared’ in VB) but also updates all references accordingly:

Refactor! Make Member Static preview

Applying the refactoring will result in the following code:

Refactor! Make Member Static result

The second refactoring is the opposite of the first one. If you have a static method – it can change it to a regular instance member, and replace its references with a new class instance creation and with an appropriate call to the source member:

Refactor! Make Member Non-static preview

Applying the refactoring will result in the following code:

Refactor! Make Member Non-static result

Both refactorings are available for methods, properties and field members of a class. You can see the ‘Member can be static‘ (or ‘Member can be shared‘ in VB) code issue if you have CodeRush Pro installed and the Code Issues feature is turned on:

CodeRush Member can be static code issue

Products: Refactor! Pro
Versions: 11.1 and up
VS IDEs: any
Updated: Oct/31/2011
ID: R043

Similar Posts: