DB NULL in C#
By FoxLearn 11/10/2024 2:12:02 AM 78
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()); } } }
- How to get application folder path in C#
- How to copy data to clipboard in C#
- How to mark a method as obsolete or deprecated in C#
- How to Call the Base Constructor in C#
- Deep Copy of Object in C#
- How to Catch Multiple Exceptions in C#
- How to cast int to enum in C#
- What is the difference between String and string in C#?