I have a little confusion with the following things:
- Null
- DBNull.Value
- ""
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 a开发者_运维百科bove things. Are they specific with datatypes? I need your valuable suggestions please.
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 (theHasValue
property will also returnfalse
)
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.
null
is internal to the language and simply means that the object reference currently doesn't refer to an actual object. Basically, a key difference between value types (int, bool, etc.) and reference types (Object, any class, etc.) is that value types are a concrete value in memory and reference types are a pointer to a representation of the object in memory. That pointer can sometimes point to, well, nothing. In which case it'snull
. It basically means "No C# object exists here."DBNull.Value
is slightly different for the purpose of working with databases. A database column can contain anull
value. However, when that data is selected into an object (such as aDataTable
) in code, there is an object there to reference as far as the code is concerned. However, that object contains a representation of anull
value from the database. Thus,DBNull.Value
exists to represent that distinction. It basically means "There is a C# object here which grabbed a value from a database, but that value isnull
.""" (or
string.Empty
if you want to use a built-in constant for that) is a valid value. It exists, it's notnull
, it's in every way astring
. It just doesn't have any characters in it. A useful tool for checking this isstring.IsNullOrEmpty()
which checks for eithernull
or the empty string.
null applies to C# null values.
System.DBNull.value applies to database specific NULL values.
When you use ExecuteScalar() it gives null if column not found or returned, but it column found and value is null there then it returns DBnull, means in a column if value is null, if will return DBnull not null.
精彩评论