Aug 19, 2015

String.IsNullOrEmpty Method

using System;

class Sample 
{
    public static void Main() 
    {
    string s1 = "abcd";
    string s2 = "";
    string s3 = null;

    Console.WriteLine("String s1 {0}.", Test(s1));
    Console.WriteLine("String s2 {0}.", Test(s2));
    Console.WriteLine("String s3 {0}.", Test(s3));
    }

    public static String Test(string s)
    {
    if (String.IsNullOrEmpty(s)) 
        return "is null or empty";
    else 
        return String.Format("(\"{0}\") is neither null nor empty", s);
    }
}
// The example displays the following output: 
//       String s1 ("abcd") is neither null nor empty.
//       String s2 is null or empty. 
//       String s3 is null or empty.
 
 
class Program
{
    static void Main()
    {
 // Example string
 string str = "";

 // Example tests
 if (str == "")
 {
     // 1
     // Test with op_Equality
     System.Console.WriteLine(1);
 }
 if (string.Equals(str, ""))
 {
     // 2
     // Test with static Equals method
     System.Console.WriteLine(2);
 }
 if (string.IsNullOrEmpty(str))
 {
     // 3
     // Test with IsNullOrEmpty
     System.Console.WriteLine(3);
 }
 if (str.Length == 0)
 {
     // 4
     // Test with Length property
     System.Console.WriteLine(4);
 }
 if (str.Equals(""))
 {
     // 5
     // Test with Equals method
     System.Console.WriteLine(5);
 }
    }
}

Output

1
2
3
4
5 

No comments:

Post a Comment