Eliminate the use of magic strings in your C# code by using the nameof
expression
Using the nameof
expression, you can retrieve the literal casing of types
, classes
, structs
, properties
, methods
, functions
, fields
, arguments
, parameters
, locals
, and more to the casing they appear in the code at compile time. This will not eliminate or solve all your "magic string" problems, but its a good start and worth discussing.
For example, getting the literal casing of an enum
value.
public enum ExportType
{
CSV,
Excel
}
nameof(ExportType.CSV); // "CSV"
nameof(ExportType.Excel); // "Excel"
nameof(ExportType); // "ExportType"
Returns the literal casing of the expression in the argument.
No more "magic strings"
If you are referring the code names of specific type names
, classes
, etc.
, strongly consider replacing those fragile magic strings with nameof
. You will not fear changing the name of a internal type, or property without fear of breaking the code. Using renaming features IDEs like Visual Studio has will rename all references anywhere in your code base referring to that expression.
Type Safety
This operation is done at compile time. Ultimately, if you are relying on the names of types
, classes
, etc.
in your code, you can introduce compile time type safety via nameof
expression into your code when referring to them.
Performance
You can eliminate a lot of reflection in your code as well that gets the names of these objects or types.
Caveats
Getting the name of generic types
nameof(T); // "T"
nameof(TEntity); // "TEntity"
In these cases, you must continue to use reflection to get the name of the type at runtime. typeof(T).Name
.
For example:
var enumValuesNames = typeof(ExportType).GetProperties().Select(p => p.Name).ToArray();