Tech Off Thread

20 posts

How to check nullness

Back to Forum: Tech Off
  • User profile image
    SlackmasterK

    (C#)  I need to check whether or not a string is null.  Every time I put it into an IF statement, if it's null it throws an exception.  So I tried to put the fired statement in a catch but it ends up firing the Catch every time.  Is there a more elegant and accurate method to test a string for nullness and get a boolean result?

  • User profile image
    Maurits

    if (s == null) { ... } should work.

    if (s.equals(null)) { ... } will never be true and will fire a NullPointerException if s is null.

  • User profile image
    SlackmasterK

    That's what I figured.  This is the line that returns the exception:

    if (logEntryDataSet.VisitorsTable[index].Browser1 == null)

    this is the exception:
    'logEntryDataSet.VisitorsTable[index].Browser1' threw an exception of type 'System.Data.StrongTypingException'
    base {System.Data.DataException} = {"The value for column 'Browser1' in table 'VisitorsTable' is DBNull."}

    I have checked and there is an entry at logEntryDataSet.VisitorsTable[index].  Browser1 is nullable and sometimes null / sometimes not, but it should work...

  • User profile image
    Maurits

    Ah...
        IsDBNull(x)
    and
        x == null
    are two different things, not to be confused.

    EDIT: See also Andrew Conrad's post on the matter

  • User profile image
    SlackmasterK

    Sweetness.

  • User profile image
    W3bbo

    Maurits wrote:
    Ah...
        IsDBNull(x)
    and
        x == null
    are two different things, not to be confused.

    EDIT: See also Andrew Conrad's post on the matter


    I tend to use "if(Foo == System.Data.DBNull.Value) {" instead of the ISDBNull function which is just a leftover from VB days.

  • User profile image
    TommyCarlier

    Or: if (Foo is DBNull) { ... }

  • User profile image
    W3bbo

    TommyCarlier wrote:
    Or: if (Foo is DBNull) { ... }


    ...C# doesn't have an "is" operator, the equivalency operator "==" works for both value and reference types.

    Which is a bit weird, considering that String is a reference type, yet VB uses the "=" operator instead of "Is"

  • User profile image
    Sven Groot

    W3bbo wrote:
    ...C# doesn't have an "is" operator

    C# does have an is operator, it compares type. Doing "instance is SomeType" is equivalent to doing "TypeOf instance Is SomeType" in VB.

    W3bbo wrote:
    Which is a bit weird, considering that String is a reference type, yet VB uses the "=" operator instead of "Is"

    This is because the Is operator tests reference equality, while the = operator for String tests string value equality:
    Dim s1 As String = "Foo"
    Dim s2 As String = "Foo"

    Dim result As Boolean = (s1 = s2) ' will be true
    result = s1 Is s2 ' false
    result = s1.Equals(s2) ' true
    result = s1.ReferenceEquals(s2) ' false

    (NOTE: In this particular example, the compiler is likely to intern the string constant so Is and ReferenceEquals would return true, but if you read the string from a file or whatever it most certainly returns false, even if the strings are identical).

    If you were to do "Dim s2 As String = s1" then both s2 and s1 actually reference the same String instance, so ReferenceEquals and Is would return true.

    In C#, the String class overloads operator== to mean string equality, meaning that since C# has no reference comparison operator like VB, if you want to test reference equality on strings, you must use ReferenceEquals or do "(object)s1 == (object)s2".

  • User profile image
    Raj Tripathi

    In Framework 2.0 String has a new more convenient method that enables you to simultaneously test whether a String is a null reference or its value is Empty. - IsNullOrEmpty.

  • User profile image
    SlackmasterK

    Maurits wrote:


    IsDBNull isn't showing up in Intellisense.  Do I need to include a specific reference?  if(x[y].z == dbnull)  isn't working either. Apparently DBNull wants to work for x[y] row but not x[y].z string. I'm not seeing an intelliSense vector for IsNullOrEmpty(x[y].z) or x[y].z.izNullOrEmpty .  Clearly I'm putting them in wrong?

  • User profile image
    SlackmasterK

    Ahh, got it!

    if (logEntryDataSet.VisitorsTable[index].IsBrowser1Null())

  • User profile image
    TommyCarlier

    W3bbo, in C#, 'is' is used to check if an object is of a given type, so 'Foo is DBNull' will be true if the object Foo is of type DBNull.

  • User profile image
    W3bbo

    TommyCarlier wrote:
    W3bbo, in C#, 'is' is used to check if an object is of a given type, so 'Foo is DBNull' will be true if the object Foo is of type DBNull.


    Yeah, my bad. I was thinking of the "is" operator as far as equality goes, not C#'s equivalent of typeof().

  • User profile image
    Sven Groot

    W3bbo wrote:
    TommyCarlier wrote: W3bbo, in C#, 'is' is used to check if an object is of a given type, so 'Foo is DBNull' will be true if the object Foo is of type DBNull.


    Yeah, my bad. I was thinking of the "is" operator as far as equality goes, not C#'s equivalent of typeof().

    C# also has typeof, but it is the equivalent of GetType in VB, and returns a System.Type object for the specified type (so "typeof(string)" returns a System.Type object for System.String, the same happens in VB with "GetType(String)")

  • User profile image
    y2k4life

    What I did was write a IsNullOrBlank in a Helper Class.

    the key is that you will want to test length because that is quicker than testing the string itself. is string == ""; sting.length == 0

    Also want to test null before lenght. The idea is that if one is true then the if stops. If the first test is for lenght on a sting that is null you will get an error. So the order of the test is important because if buffer == null the other 'or' part of the if will not execute.

    public class StringHelper
    {
        public static bool IsNullOrBlank(string testBuffer)
        {
           if(testBuffer == null || testBuffer.Length == 0)
               return true;
           else
               return false;
        }
    }

    if(!StringHelper.IsNullOrBlank(buffer))
      buffer not null
    else
      buffer is null

    if(StringHelper.IsNullOrBlank(buffer))
      buffer is null
    else
      buffer is not null


    - g


     

  • User profile image
    Sven Groot

    y2k4life wrote:
    public class StringHelper
    {
        public static bool IsNullOrBlank(string testBuffer)
        {
           if(testBuffer == null || testBuffer.Length == 0)
               return true;
           else
               return false;
        }
    }

    I realize some people prefer to do this for readability, but just to be sure: you do realize you can condense that down to "return testBuffer == null || testBuffer.Length == 0;", I hope. Smiley

  • User profile image
    Maurits

    The Perler in me wants to write: s ??= ""; Wink

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.