{"record":{"id":"b8962df2377121f6","repo":"microsoft/aspire","slug":"cannot-cast-paramname-from-value-gettype-tostring-null-to","errorCode":null,"errorMessage":"Cannot cast '{paramName}' from '{value?.GetType().ToString() ?? \"null\"}' to '{typeof(T)}'","messagePattern":"Cannot cast '(.+?)' from '(.+?)' to '(.+?)'","errorType":"validation","errorClass":"InvalidCastException","httpStatus":null,"severity":"error","filePath":"src/Vendoring/OpenTelemetry.Instrumentation.ConfluentKafka/Shared/Guard.cs","lineNumber":179,"sourceCode":"        public static void ThrowIfOutOfRange(double value, [CallerArgumentExpression(\"value\")] string? paramName = null, double min = double.MinValue, double max = double.MaxValue, string? minName = null, string? maxName = null, string? message = null)\n        {\n            Range(value, paramName, min, max, minName, maxName, message);\n        }\n\n        /// <summary>\n        /// Throw an exception if the value is not of the expected type.\n        /// </summary>\n        /// <param name=\"value\">The value to check.</param>\n        /// <param name=\"paramName\">The parameter name to use in the thrown exception.</param>\n        /// <typeparam name=\"T\">The type attempted to convert to.</typeparam>\n        /// <returns>The value casted to the specified type.</returns>\n        [DebuggerHidden]\n        [MethodImpl(MethodImplOptions.AggressiveInlining)]\n        public static T ThrowIfNotOfType<T>([NotNull] object? value, [CallerArgumentExpression(\"value\")] string? paramName = null)\n        {\n            if (value is not T result)\n            {\n                throw new InvalidCastException($\"Cannot cast '{paramName}' from '{value?.GetType().ToString() ?? \"null\"}' to '{typeof(T)}'\");\n            }\n\n            return result;\n        }\n\n        [DebuggerHidden]\n        [MethodImpl(MethodImplOptions.AggressiveInlining)]\n        private static void Range<T>(T value, string? paramName, T min, T max, string? minName, string? maxName, string? message)\n            where T : IComparable<T>\n        {\n            if (value.CompareTo(min) < 0 || value.CompareTo(max) > 0)\n            {\n                var minMessage = minName != null ? $\": {minName}\" : string.Empty;\n                var maxMessage = maxName != null ? $\": {maxName}\" : string.Empty;\n                var exMessage = message ?? string.Format(\n                    CultureInfo.InvariantCulture,\n                    \"Must be in the range: [{0}{1}, {2}{3}]\",\n                    min,","sourceCodeStart":161,"sourceCodeEnd":197,"githubUrl":"https://github.com/microsoft/aspire/blob/25830f84bd145686607ad00c057b3f84e2e51d43/src/Vendoring/OpenTelemetry.Instrumentation.ConfluentKafka/Shared/Guard.cs#L161-L197","documentation":"Thrown by Guard.ThrowIfNotOfType<T> in the vendored ConfluentKafka instrumentation's Guard helper when the supplied object cannot be cast to the expected type T. It throws InvalidCastException naming the argument, its actual runtime type, and the target type. Used to validate downcasts of loosely typed payloads or options.","triggerScenarios":"Passing an object to a generic API expecting a specific type T, e.g. an options/state object of the wrong concrete type, or an object[]/object payload that is not T.","commonSituations":"Passing an incompatible options class after an API change or version mismatch of instrumentation packages; sharing one state object across APIs that expect different types; deserialized payloads typed as object.","solutions":["Read the actual type from the exception message and construct/pass an instance of the expected type T instead.","Check for package version mismatches where two assemblies disagree on the options type.","Use pattern matching (obj is T t) at the call site to handle mismatches explicitly before calling."],"exampleFix":"// before\nobject opts = new SqlServerOptions();\nGuard.ThrowIfNotOfType<KafkaOptions>(opts);\n\n// after\nobject opts = new KafkaOptions();\nvar kafkaOpts = Guard.ThrowIfNotOfType<KafkaOptions>(opts);","handlingStrategy":"type-guard","validationCode":"if (value is not T expected)\n{\n    throw new ArgumentException($\"expected {typeof(T)}, got {value?.GetType()}\", nameof(value));\n}","typeGuard":"static bool IsOfType<T>([NotNullWhen(true)] object? value, [NotNullWhen(true)] out T? typed) where T : class\n{\n    typed = value as T;\n    return typed is not null;\n}","tryCatchPattern":"try\n{\n    instrumented.WithOptions(opts);\n}\ncatch (InvalidCastException ex)\n{\n    logger.LogError(ex, \"options object had the wrong type; check package version alignment\");\n}","preventionTips":["Pass strongly typed options rather than object","Keep all OpenTelemetry instrumentation packages on aligned versions","Use pattern matching on loosely typed payloads before calling guarded APIs"],"tags":["invalid-cast","type-mismatch","opentelemetry","kafka"],"backgroundTag":"type-mismatch","analyzedSha":"25830f84bd145686607ad00c057b3f84e2e51d43","analyzedAt":"2026-09-16T11:10:06.193Z","contentChangedAt":"2026-09-16T11:10:06.193Z","schemaVersion":2},"datasetVersion":"2026-09-21T09:17:21.228Z"}