How to Check Null Value in C#

There are two types of null values to evaluate when programming. The first type is a null value that can be assigned to a variable like a string. The null value is placed as a holder value and replaced when the variable is used at a later point in the code. The second value is the "DBNull" value that is returned from a database. These two types are treated differently by the compiler.

Instructions

  1. Check "null" Values

    • 1

      Create the variable. A variable must be declared before using it. The code below allocates memory and declares the variable for use.
      string myNullVar = null;
      The code uses the "null" value assignment for the new variable.

    • 2

      Check if the variable is null. The code below checks if the variable is null. If it is null, the code assigns it a color value.
      if(myNullVar == null) {
      myNullVar = "purple";
      }

    • 3

      Check if the variable is not null. In some cases, you may wan to reassign the variable back to null. The following code checks if the variable is not null, and assigns it a null value.
      if(myNullVar != null) {
      myNullVar = null;
      }

    Check for DBNull Values

    • 4

      Declare a variable. Just like section 1, to check for DBNull, a variable needs to be declared. However, the variable is assigned the DBNull value.
      string myNullVar = System.DBNull;

    • 5

      Use the "Equals()" method from the string class to check for the DBNull value. The code below checks for this value and assigns myNullVar a color.
      if (myNullVar.Equals(System.DBNull.Value)) {
      myNullVar = "purple";
      }

    • 6

      Evaluate if the variable is not null. Similar to section one, you may want to check if the variable is not null to reassign it back to DBNull. The "!" character evaluates to "not" in the following example.
      if(!myNullValue.Equals(System.DBNull.Value)) {
      myNullValue = System.DBNull;
      }

Related Searches:

References

Comments

Related Ads

Featured