{"record":{"id":"d4d0891d50f628da","repo":"elsa-workflows/elsa-core","slug":"variable-name-already-exists-in-the-context","errorCode":null,"errorMessage":"Variable {name} already exists in the context.","messagePattern":"Variable (.+?) already exists in the context\\.","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"src/modules/Elsa.Workflows.Core/Extensions/ExpressionExecutionContextExtensions.cs","lineNumber":158,"sourceCode":"            foreach (var block in context.Memory.Blocks.Where(b => b.Value.Metadata is VariableBlockMetadata))\n            {\n                var metadata = block.Value.Metadata as VariableBlockMetadata;\n                if (metadata!.Variable.Name == name)\n                    return block.Value;\n            }\n\n            return localScopeOnly ? null : context.ParentContext?.GetVariableBlock(name);\n        }\n\n        /// <summary>\n        /// Creates a named variable in the context.\n        /// </summary>\n        public Variable CreateVariable<T>(string name, T? value, Type? storageDriverType = null, Action<MemoryBlock>? configure = null)\n        {\n            var existingVariable = context.GetVariable(name, localScopeOnly: true);\n\n            if (existingVariable != null)\n                throw new($\"Variable {name} already exists in the context.\");\n\n            var variable = new Variable(name, value)\n            {\n                StorageDriverType = storageDriverType ?? typeof(WorkflowInstanceStorageDriver)\n            };\n        \n            var parsedValue = variable.ParseValue(value);\n\n            // Find the first parent context that has a variable container.\n            // If not found, use the current context.\n            var variableContainerContext = context.GetVariableContainerContext();\n\n            variableContainerContext.Set(variable, parsedValue, configure);\n            return variable;\n        }\n\n        /// <summary>\n        /// Returns the first parent context that contains a variable container.","sourceCodeStart":140,"sourceCodeEnd":176,"githubUrl":"https://github.com/elsa-workflows/elsa-core/blob/fe9217bdfa0e27f0e09e45006eb6898f616e513d/src/modules/Elsa.Workflows.Core/Extensions/ExpressionExecutionContextExtensions.cs#L140-L176","documentation":"CreateVariable on ExpressionExecutionContext creates a brand-new variable in the current (local) memory scope. If a variable with the same name already exists in that local scope, creating it again would silently shadow or corrupt state, so the extension throws this exception. Use SetVariable semantics instead when overwriting is intended.","triggerScenarios":"Calling expressionExecutionContext.CreateVariable<T>(name, ...) when context.GetVariable(name, localScopeOnly: true) already returns a value — i.e. the name is already declared in the current memory scope.","commonSituations":"Re-running an expression/script block that creates variables on each pass without checking existence; two script activities in the same scope declaring the same variable name; workflow retries or bookmark resumption re-executing the creation code path.","solutions":["Guard the call: only create when the variable does not already exist locally, otherwise set its value.","Use SetVariable (memory.Set / variable.Set semantics) to assign to an existing variable instead of CreateVariable.","Rename the variable to be unique per scope or declare it once in the enclosing workflow/composite.","Wrap creation logic so it executes only once (e.g. first-visit check via `context.GetIsTriggeredByBookmark` or similar first-execution checks)."],"exampleFix":"// before\ncontext.CreateVariable(\"total\", 0); // throws if 'total' exists in local scope\n// after\nif (context.GetVariable(\"total\", localScopeOnly: true) == null)\n    context.CreateVariable(\"total\", 0);\nelse\n    context.SetVariable(\"total\", 0);","handlingStrategy":"validation","validationCode":"if (context.GetVariable(name, localScopeOnly: true) != null)\n    throw new InvalidOperationException($\"Variable '{name}' already exists; use SetVariable to assign\");","typeGuard":"bool exists = context.GetVariable(name, localScopeOnly: true) != null;","tryCatchPattern":"try { context.CreateVariable(name, value); } catch (Exception ex) { logger.LogError(ex, \"Variable {Name} already declared in local scope\", name); }","preventionTips":["Check existence before CreateVariable; use SetVariable for assignment","Give script-created variables unique names per scope","Ensure variable-creation code does not re-run on bookmark resumption"],"tags":["variables","expressions","csharp"],"backgroundTag":"duplicate-definition-conflict","analyzedSha":"fe9217bdfa0e27f0e09e45006eb6898f616e513d","analyzedAt":"2026-09-13T20:32:34.702Z","contentChangedAt":"2026-09-13T20:32:34.702Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}