Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When we have to use DBNull.Value, null and "" in C#.Net?

I have a little confusion with the following things:

  1. Null
  2. DBNull.Value
  3. ""

When I use Conditional Statements OR while assigning values, I am a little bit confused with these things. Sometimes it throws error and some times it works. I want to know when I want to use the above things. Are they specific with datatypes? I need your valuable suggestions please.

like image 948
thevan Avatar asked Jun 17 '11 12:06

thevan


1 Answers

null is one of two things:

  • a reference that doesn't actually point to an object - just a "nothing" indicator (essentially, it is the value 0 as a reference)
  • a Nullable<T> struct, which does not currently have a value (the HasValue property will also return false)

DBNull is specific to some parts of ADO.NET to represent null in the database. I have yet to think of a good reason why they didn't just use regular null here.

"" is a string literal with length zero - a perfectly valid, but empty, string. The significance of this is that between null string and a "" string, instance methods like value.Trim() will behave differently; null.Trim() will throw an exception; "".Trim() is just "". In general, using string.IsNullOrEmpty(value) as a test makes this distinction go away.

like image 151
Marc Gravell Avatar answered Sep 18 '22 01:09

Marc Gravell