Constants
What are constants?
Constants are named values that remain unchanged throughout the application execution. Unlike enums which represent a set of related values, constants are individual immutable values that can be of various types (string, number, boolean, etc.). Constants provide a centralized way to manage configuration values, magic numbers, and other fixed values used across your application.
How to create constants
To create constants, you need to first create a constants static class, then add individual constants to it.
Creating a constants static class
To create a constants static class, you can click in the menu on the + button of the Constants classes item under one of these folders of a module:
Sharedfolder for constants used in both backend and frontendBackendfolder for constants used only in backend codeFrontendfolder for constants used only in frontend code
The folder where you create the constants static class will determine its default scope, but you can still modify the scope later if needed.
Name
This is the name of the constants static class. It will be used to generate the corresponding C# static class. The name should follow C# naming conventions (PascalCase).
Description
This optional property is the short description of what the constants static class will be used for. It will be displayed by the code editor intellisense.
Module
This is the module to which the constants static class will be associated.
Scope
By default, a constants static class is shared between the backend and frontend. However, if you want to reduce the scope of use, you can specify a scope. This scope optimizes generation to generate only the code corresponding to the scope (frontend / backend).
- Shared: The constants static class can be used in both frontend and backend code.
- Backend: The constants static class can only be used in backend code. No frontend code is generated for this constants static class.
- Frontend: The constants static class can only be used in frontend code. No backend code is generated for this constants static class.
Adding constants to a static class
Once you have created a constants static class, you can add individual constants to it by clicking the Add button in the constants section.
Name
This is the name of the constant. It will be used as the property name in the generated static class. The name should follow C# naming conventions (PascalCase).
Description
This optional property is the short description of what the constant will be used for. It will be displayed by the code editor intellisense.
.NET data type
This is the C# data type of the constant. Only types that can be used as C# constants are supported:
- string: Text values
- bool: Boolean values (true/false)
- byte, sbyte: 8-bit integers
- short, ushort: 16-bit integers
- int, uint: 32-bit integers
- long, ulong: 64-bit integers
- float: Single-precision floating-point
- double: Double-precision floating-point
- decimal: High-precision decimal
- char: Single character
Value
This is the C# value of the constant. The value must be provided using valid C# syntax and must match the specified .NET data type.
Examples by data type:
- string:
"Hello World"or"API_ENDPOINT" - bool:
trueorfalse - int:
42or-10 - long:
42Lor-10L - float:
3.14for-1.5f - double:
3.14159or-1.5 - decimal:
99.99mor0.01m - char:
'A'or'1'
Special case for string constants:
When the string constant value corresponds to the constant name, it's recommended to use nameof(ConstantName) as the value. This provides better maintainability and refactoring support.
For example, if you have a constant named ApiEndpoint and want its value to be the string "ApiEndpoint", use:
Value: nameof(ApiEndpoint)
This will generate:
public const string ApiEndpoint = nameof(ApiEndpoint); // Results in "ApiEndpoint"
Module
This is the module to which the constant will be associated.
How to use constants?
Constants are translated into C# static classes with constant fields, you can use these constants in both client side and server side code of the cluster.
Usage example
// Using a string constant
string connectionTimeout = DatabaseConstants.ConnectionTimeout; // "30s"
// Using an integer constant
int maxRetries = ApiConstants.MaxRetryAttempts; // 3
// Using a boolean constant
bool enableLogging = FeatureFlags.EnableDetailedLogging; // true
// Using a decimal constant
decimal taxRate = BusinessConstants.DefaultTaxRate; // 0.20m
// Using a long constant
long maxFileSize = FileConstants.MaxUploadSize; // 5000000L
Frontend transpilation behavior
On the frontend, constants are replaced by their actual values during the transpilation process. This means that in the generated TypeScript code, you will see the hard-coded values instead of constant references.
For example, if you have:
string message = Messages.WelcomeText;
In the generated TypeScript, this becomes:
const message = "Welcome to the application";
This optimization eliminates the need for constant lookups at runtime and can improve performance.
Finding hardcoded strings with "Hardcoded strings"
The "Hardcoded strings" screen displays a list of hardcoded strings found in both server and client-side C# code. This tool can help identify string literals that could potentially be replaced with constants or resources to improve code maintainability.
Accessing the screen
The "Hardcoded strings" screen is available in Neos Studio:
- Open Neos Studio in your browser
- In the left navigation panel, expand the Tools section
- Click on Hardcoded strings
Features
The screen provides:
- List of hardcoded strings: Displays all string literals found in the codebase
- File location: Shows the file path where each string is located
- Line and column numbers: Indicates the exact position of the string in the file
- Occurrences count: Shows how many times each string appears across the codebase
- Suggestions: Displays an information icon when a hardcoded string matches an existing constant, suggesting a potential replacement
- Code preview: Shows the code context where the string is used (YAML or C# syntax highlighting)
- Search functionality: Allows searching through the string text and file paths
Cache refresh
On first load, the tool creates a server-side cache of hardcoded strings. To get updated results after code changes, use the "Cache reset" action to refresh the data.
Usage considerations
While this tool helps identify hardcoded strings, not every string needs to be replaced with a constant. Consider the context and whether the string is:
- Used in multiple locations
- A configuration value that might change
- A business rule or status that could benefit from centralization
Benefits of using constants
- Centralized management: All constant values are defined in one place
- Type safety: Constants are strongly typed and validated at compile time
- IntelliSense support: IDE provides autocompletion for constant names
- Maintainability: Easy to update values across the entire application
- Documentation: Constants can be self-documented with descriptions
Best practices
- Use descriptive names that clearly indicate the purpose of the constant
- Group related constants in the same static class (e.g.,
ApiConstants,UiConstants,DatabaseConstants) - Use appropriate scopes to avoid unnecessary code generation
- Document complex constants with meaningful descriptions
- Consider using enums instead of constants when you have a set of related values that represent choices or states
Type-specific best practices
- String constants: Always use double quotes (
"value") and considernameof()when the value matches the constant name - Numeric constants: Use appropriate suffixes (
Lfor long,ffor float,mfor decimal) to ensure correct type inference - Boolean constants: Use
trueorfalseliterals directly - Character constants: Use single quotes (
'A') for char values