Azure Bicep recently introduced the nameof() function—now you can derive property or variable names as strings directly in your code. Inspired by C#, this addition helps to reduce typos and improve maintainability in Bicep templates.
What Is nameof()?
The nameof() function evaluates a symbolic name (like a variable or object property) into its string representation at compile time. Instead of hardcoding a string (e.g., “backendA”), you use nameof(backends.backendA), which Bicep compiles as “backendA”.
Why It Matters
Basic Usage
Imagine you have a Bicep object:
var backends = {
backendA: {
url: 'https://a.example'
}
backendB: {
url: 'https://b.example'
}
}
Without nameof(), you’d write:
var apiSpecs = {
apiA: {
backend: 'backendA'
}
}
This leaves room for typos like ‘backenda’ or misalignment if you rename the variable.
Use nameof() Instead
var apiSpecs = {
apiA: {
backend: nameof(backends.backendA)
}
}
Now:
Real-World Use Cases
| Scenario | Benefit |
|---|---|
| Dictionary or map object | Reference object keys dynamically without hard-coded strings |
| Role assignments & naming | Generate consistent role-definition or assignment IDs based on resource names |
| Module reuse | Pass property names to modules safely and refactor-friendly |
| Validation & policy checks | Compare expected keys or names as strings in conditions |
Example: Generate a Variable Name
var skuSettings = {
standard: {
count: 2
}
premium: {
count: 5
}
}
var selectedSku = skuSettings['standard']
var skuName = nameof(skuSettings.standard)
// skuName == 'standard'
This makes it safe to build naming conventions like: api-${skuName}.
When to Use nameof() & When Not To
How to Get It
Make sure you’re using Bicep CLI v0.31 or higher.
Check your version:
bicep --version
Update if needed via:
az bicep upgrade
Summary
The nameof() function in Bicep brings:
Adopt it today for map objects, naming patterns, assignment definitions—even policy logic. It’s a small feature that greatly improves long-term template quality.