开发者

string comparison in c#

开发者 https://www.devze.com 2023-02-06 10:03 出处:网络
I want to compare two strings and one of them may be a null str开发者_运维知识库ing, am using StringComparison.InvariantCultureIgnoreCase feature of C#. This throws an exception in runtime when a null

I want to compare two strings and one of them may be a null str开发者_运维知识库ing, am using StringComparison.InvariantCultureIgnoreCase feature of C#. This throws an exception in runtime when a null string is encountered. What shall I do to be able to compare even null strings?


As well as the options already given to you, you can consider using StringComparer.InvariantCultureIgnoreCase instead. StringComparer handles nulls without throwing exceptions:

using System;

class Test
{
    static void Main()
    {
        StringComparer comparer = StringComparer.InvariantCultureIgnoreCase;
        Console.WriteLine(comparer.Compare("a", "A"));
        Console.WriteLine(comparer.Compare("a", null));
        Console.WriteLine(comparer.Compare(null, "A"));
    }
}


use

 string.Compare(s1, s2, StringComparison.InvariantCultureIgnoreCase);

benefit of using this is that it will return 0 (equal) if two strings are null - which is the expected result.


You can use

if (String.IsNullOrEmpty(yourString)) { // If true... }


Depens on what do you want to happen when string is null.

You may simply fall back to empty string like this: (str ?? "").Compare(...)


This from a post I remember @Jon Skeet answering a question about comparing:

string myCompareString = "compare me";

if(myCompareString.Equals(myOtherMaybeNullString, StringComparison.InvariantCultureIgnoreCase))
{
   // blah blah
}

Causes the comparison against a string you know is not null to a string that might be null (unless you are comparing 2 potentially null strings).


Just as a extra option String.Equals handles null so you could also use:

using System;

class Test
{
    static void Main()
    {
            var a = String.Equals("test", "Test", StringComparison.InvariantCultureIgnoreCase);
            var b = String.Equals("test", null, StringComparison.InvariantCultureIgnoreCase);
            var c = String.Equals(null, "Test", StringComparison.InvariantCultureIgnoreCase);
            var d = String.Equals(null, null, StringComparison.InvariantCultureIgnoreCase);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消