Check for length too when you check for null strings in VB.Net and C#

Its a good idea to check for null object reference to prevent NullReferenceException when it comes to objects but in case of Strings sometimes you get a string without any value or called as Empty string. I have faced this a lot of time when I handle exceptions and the error message ( which is a string ) turns out to be empty hence there is no meaning to show that message or store it in database. So the good idea is to check for null and for emptiness ( zero length string ) bot at the same time.

‘[ Visual Basic ]

Sub CheckNullString ( ByVal msg as String )

if msg is nothing or Else msg.length = 0 Then Exit Sub

‘ Do whatever you want in case both are false.

End Sub

// C#

public void checkNullString ( string msg )

{

if ( msg == null || msg.Length == 0 ) return;

// Do whatever you want here in case both are false.

}

This is one good way I was able to find . How do you check your strings ? Do share with us in comments .

LEAVE A REPLY

Please enter your comment!
Please enter your name here