DB NULL in C#
By Tan Lee Published on Nov 10, 2024 659
It's common for C# developers to confuse DBNull.Value
with null
because both represent the absence of a value, but they are used in different contexts:
DBNull
represents a missing or undefined value from a database. It's used in ADO.NET to representNULL
values from a database field.null
represents the absence of a reference to an object in C#.
For example:
SqlDataReader reader = cmd.ExecuteReader(); reader.Read(); object obj = reader["state"]; if (obj == null) { return false; } //... return true;
When working with databases in C# and using a DataReader
, it's important to understand the distinction between null
and DBNull
. While it might seem intuitive that a NULL
value from a database would return null
in C#, the correct return type is actually System.DBNull
.
object obj = reader["state"]; if (obj == DBNull.Value) { return false; } //... return true;
What if someone writes code like this?
object obj = rs["state"]; if (obj == null || obj == DBNull.Value) { }
It's not wrong, but variable obj
will never be null, so "obj == null" is unnecessary.
In .NET, there is a built-in method called Convert.IsDBNull()
that simplifies checking for database NULL
values, making your code clearer and more concise.
using (var connection = new SqlConnection(connectionString)) { string query = "SELECT state FROM Users WHERE UserId = 1"; var command = new SqlCommand(query, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { object state = reader["state"]; if (!Convert.IsDBNull(state)) { Console.WriteLine("State: " + state.ToString()); } } }
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization