C#
SQL
AddWithValue
NULL parameter
exception handling

Exception when AddWithValue parameter is NULL

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

AddWithValue looks convenient in ADO.NET, but null handling and type inference often make it unreliable in production code. The common failure is passing C sharp null and expecting SQL NULL behavior with the correct SQL type. A robust approach is to define parameter metadata explicitly and assign DBNull.Value when values are missing.

Why AddWithValue Fails with Null Inputs

AddWithValue infers SQL type from the runtime value you pass. If that value is null, there is no concrete CLR type to infer from. Even when the call does not throw immediately, inferred type and size can mismatch your schema.

Typical consequences:

  • conversion exceptions in stored procedures
  • implicit conversion in SQL Server that hurts index usage
  • unstable query plans due to wrong parameter type or length

Remember that C sharp null and SQL NULL are different representations. ADO.NET expects DBNull.Value for database null.

Problem Pattern and Safe Replacement

Risky pattern:

csharp
string? nickname = null;
cmd.Parameters.AddWithValue("@Nickname", nickname);

Safer pattern:

csharp
1using System.Data;
2using Microsoft.Data.SqlClient;
3
4string? nickname = null;
5
6var p = cmd.Parameters.Add("@Nickname", SqlDbType.NVarChar, 50);
7p.Value = (object?)nickname ?? DBNull.Value;

This makes intent explicit and keeps type mapping stable across environments.

Full Insert Example with Nullable Values

csharp
1using System;
2using System.Data;
3using Microsoft.Data.SqlClient;
4
5var connectionString = "Server=localhost;Database=AppDb;Trusted_Connection=True;Encrypt=False";
6
7using var conn = new SqlConnection(connectionString);
8conn.Open();
9
10using var cmd = new SqlCommand(
11    "INSERT INTO Users(DisplayName, Age, LastLoginUtc) VALUES(@DisplayName, @Age, @LastLoginUtc)",
12    conn
13);
14
15string? displayName = null;
16int? age = null;
17DateTime? lastLoginUtc = DateTime.UtcNow;
18
19cmd.Parameters.Add("@DisplayName", SqlDbType.NVarChar, 100).Value =
20    (object?)displayName ?? DBNull.Value;
21cmd.Parameters.Add("@Age", SqlDbType.Int).Value =
22    (object?)age ?? DBNull.Value;
23cmd.Parameters.Add("@LastLoginUtc", SqlDbType.DateTime2).Value =
24    (object?)lastLoginUtc ?? DBNull.Value;
25
26cmd.ExecuteNonQuery();

This code is verbose by design, and that verbosity prevents hidden inference bugs.

Stored Procedure Calls Need Exact Types

Stored procedures are stricter than ad hoc SQL because parameter names, types, and sizes are part of the contract.

csharp
1using var cmd = new SqlCommand("dbo.UpdateProfile", conn)
2{
3    CommandType = CommandType.StoredProcedure
4};
5
6cmd.Parameters.Add("@UserId", SqlDbType.Int).Value = userId;
7cmd.Parameters.Add("@Bio", SqlDbType.NVarChar, 400).Value =
8    (object?)bio ?? DBNull.Value;
9
10cmd.ExecuteNonQuery();

When procedure signatures and ADO.NET parameter definitions align, you avoid many intermittent runtime failures.

Helper Methods to Reduce Boilerplate

You can keep explicit typing while reducing repeated null mapping.

csharp
static object ToDbValue(string? value) => (object?)value ?? DBNull.Value;
static object ToDbValue(int? value) => value.HasValue ? value.Value : DBNull.Value;
static object ToDbValue(DateTime? value) => value.HasValue ? value.Value : DBNull.Value;

Usage:

csharp
cmd.Parameters.Add("@Comment", SqlDbType.NVarChar, 500).Value = ToDbValue(comment);

Keep helpers simple and type specific so debugging remains straightforward.

Performance and Plan Quality

AddWithValue can infer string parameters as broad lengths that differ from table definitions. SQL Server may then perform implicit conversion and skip index seeks.

For high traffic endpoints, explicit parameter size often improves:

  • plan stability
  • CPU usage
  • latency variance

Correct typing is a reliability and performance practice, not only a style preference.

Troubleshooting Checklist

When null related parameter exceptions appear:

  1. Inspect target column type and nullability.
  2. Log parameter names, SQL types, sizes, and runtime values.
  3. Replace AddWithValue with explicit Add calls.
  4. Map all nullable values through DBNull.Value.
  5. Recheck stored procedure parameter definitions.

This process identifies root cause quickly and avoids random trial and error.

Common Pitfalls

Passing raw C sharp null without conversion to DBNull.Value is the most common error.

Another pitfall is using explicit SQL types but omitting string length, which still causes mismatches. Always define length for NVarChar and similar types.

Teams also mix System.Data.SqlClient and Microsoft.Data.SqlClient packages inconsistently. Standardize provider choice in one codebase to reduce surprises.

Summary

  • 'AddWithValue is convenient but risky for null values and type inference.'
  • Use explicit SqlDbType plus DBNull.Value mapping for nullable inputs.
  • Match stored procedure signatures exactly, including length and precision.
  • Strong parameter definitions improve both correctness and query performance.
  • Keep helper methods small so null conversion remains consistent and readable.

Course illustration
Course illustration

All Rights Reserved.