What is the difference between null and System.DBNull.Value?

后端 未结 6 552
忘了有多久
忘了有多久 2020-11-22 11:02

Is there any difference between null and System.DBNull.Value? If yes, what is it?

I noticed this behavior now -

while (rdr.Read())
{
    if (rdr[\"I         


        
6条回答
  •  不思量自难忘°
    2020-11-22 11:08

    Well, null is not an instance of any type. Rather, it is an invalid reference.

    However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.

    *We would normally say null, but I don't want to confound the issue.

    So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).

    Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.

提交回复
热议问题