3

When modifying data in a SQL Server database you can use either System.DBNull.Value or null to represent a NULL value. Both of these will work and will set the proper value to NULL.

My question is - which of these is preferred, and why? Are there certain cases where one should be used in place of the other?

Yuck
  • 49,664
  • 13
  • 105
  • 135
Royi Namir
  • 144,742
  • 138
  • 468
  • 792

2 Answers2

2

From System.DBNull.Value != null, and by testing this code:

var result = (System.DBNull.Value == null); // this is always false

We can see that the CLR doesn't treat them the same way. When retrieving data from a database we need to check for DBNull.Value and not a null reference.

Although it doesn't matter which we use to INSERT or UPDATE data, I would tend to stick with DBNull.Value for consistency through data access code.

There are a variety of other opinions in the question C# Database Access: DBNull vs null

Community
  • 1
  • 1
Yuck
  • 49,664
  • 13
  • 105
  • 135
  • your first part isnt relevant to the question :) - Ive already ansered that my self in the Question Itself.` still , which of these is preferred, and why? ` (in inserting mode.) ? – Royi Namir Oct 27 '11 at 15:18
  • 1
    It's relevant in that it sets up my position which is that **since it matters when reading** you should stay consistent and **use it when inserting or updating**. – Yuck Oct 27 '11 at 15:19
  • I heard that there is a dependencefor RDBMS type..no ? – Royi Namir Oct 27 '11 at 15:20
  • Your question is tagged for SQL Server where they are treated the same. I can't speak to other RDBMS connectors. I did notice that one of the answers on the related question seems to indicate that Oracle requires the use of `DBNull`. – Yuck Oct 27 '11 at 15:22
0

DBNull is representative of a variant and is not type-specific. In a general context, I would expect a performance hit anywhere you have a construct that expects a strongly-typed dataset and has to convert DBNull to a "typed-NULL".

Quantum Elf
  • 752
  • 4
  • 9