Home > Code Analysis > Code Issues specific for declaring variables and constants

Code Issues specific for declaring variables and constants

August 9th, 2012

In addition to code issues specific for declaring types, CSharp and Visual Basic language specifications have a few restrictions on declaring constant or simple variable declarations. Having this issue in the code editor right in front of a developer allows him to fix the issue immediately without compiling the project.

Constant cannot be marked static

Cause:

A const member is considered static by the compiler. Although constants are considered static members, a constant declaration neither requires nor allows a static modifier. In other words, if a variable is marked as const, it is also static and there’s no need to mark it static.

Sample:

CodeRush Constant сannot be marked static

How to fix:

  • Remove the static modifier from the const declaration:

CodeRush Constant сannot be marked static fix

Cannot declare variable of static type

Cause:

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated, because static classes are sealed. You cannot use the new keyword to create a variable of a static class. Creating a variable of a static class is basically the same as creating a class that contains only static members and a private constructor. The compiler will guarantee that instances of a static class cannot be created.

Sample:

CodeRush Cannot declare variable of static type

How to fix:

Because there is no instance variable, you access the members of a static class by using the class name itself. Remove the variable and access the type directly:

CodeRush Cannot declare variable of static type fix

Array elements cannot be of static type

Cause:

The cause of this issue is the same as the cause of the previous issue about creating a variable of a static type. An array of the static type does not make sense, since array elements are instances, but it is not possible to create instances of static types.

Sample:

CodeRush Array elements cannot be of static type

How to fix:

  • Do not create an array of the static type and access the type directly:

CodeRush Array elements cannot be of static type Fix

  • Make the type non-static if appropriate.
—–
Products: CodeRush Pro
Versions: 12.1 and up
VS IDEs: 2008 and up
Updated: Aug/09/2012
ID: C175

Similar Posts: