Code Issues specific for declaring variables and constants
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:
How to fix:
- Remove the static modifier from the const declaration:
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:
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:
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:
How to fix:
- Do not create an array of the static type and access the type directly:
- Make the type non-static if appropriate.