Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IsNullOrEmpty with Object

Tags:

IsNullOrEmpty is used with strings to check if a string is null or empty. Is there an equivalent with an object to see if any object is null or not? I assume we can do

    obj1 != null 

but not sure if there is any other way...

like image 997
Nate Pet Avatar asked Jan 16 '12 23:01

Nate Pet


People also ask

How do you check if an object is null or empty?

To test if an object is null: instead of using (obj1 == null) you can use bool bIsNull = object. Equals(obj1, null);

Is null an object in C#?

null (C# Reference)The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables.

What is the difference between IsNullOrEmpty and IsNullOrWhiteSpace?

The main difference between IsNullOrEmpty and IsNullOrWhiteSpace in C# is that IsNullOrEmpty checks if there's at least one character, while IsNullOrWhiteSpace checks every character until it finds a non-white-space character.


2 Answers

I found that DataGridViewTextBox values and some JSON objects don't equal Null but instead are "{}" values. Comparing them to Null doesn't work but using these do the trick:

if (cell.Value is System.DBNull)

if (cell.Value == System.DBNull.Value)

A good excerpt I found concerning the difference between Null and DBNull:

Do not confuse the notion of null in an object-oriented programming language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.

You can learn more about the DBNull class here.

like image 166
Zorgarath Avatar answered Sep 30 '22 02:09

Zorgarath


a null string is null, an empty string is ""

isNullOrEmpty requires an intimate understanding about the implementation of a string. If you want one, you can write one yourself for your object, but you have to make your own definition for whether your object is "empty" or not.

ask yourself: What does it mean for an object to be empty?

like image 31
Sam I am says Reinstate Monica Avatar answered Sep 30 '22 02:09

Sam I am says Reinstate Monica