0
static void Main(string[] args)
    {
        string string1 = "  "; // it can be NULL and any word too
        string string2 = null; // it can be NULL and any word too

        if (string.IsNullOrEmpty(string1))
        {
            if (string.IsNullOrEmpty(string2))
            {
                Console.WriteLine("Both the string Null & equal");
            }
        }
        else
        {
            if (!string.IsNullOrEmpty(string2))
            {
               if(string1.Trim().Equals(string2.Trim(),StringComparison.OrdinalIgnoreCase))
                {
                    Console.WriteLine("Both the string has value& equal");
                }
            }
        }
    }

This code checks for NULL or value of both the string ultimately to confirm both the string is same. Importantly it has to trim the white space to make it comparable and same time if the string is NULL then it can't be trimmed.

Going through all possible conditions, I have written this block of code and still believing someone can make it more efficient in terms of efficiency.

Thank you!

Shiv
  • 129
  • 2
  • 10
  • *still believing someone can make it more efficient* What do you mean by efficiency here? – Sriram Sakthivel Mar 18 '16 at 17:37
  • Why don't you compare with ignoring case by converting both to lowercase – anomepani Mar 18 '16 at 17:38
  • Efficient meant to - Less no. of lines of code and memory consumption if any. – Shiv Mar 18 '16 at 17:39
  • 1
    To get less lines of code just remove all new lines :) I see nothing particularly wrong with code posted. You may consider more general approaches covered in http://stackoverflow.com/questions/4718965/c-sharp-string-comparison-ignoring-spaces-carriage-return-or-line-breaks. – Alexei Levenkov Mar 18 '16 at 17:41
  • In the opening bit of logic, it treats one being null and one being an empty string as being equal. Is this really the desired comparison? I suspect you may wish to use IsNull here rather than IsNullOrEmpty. The Trim in the second bit of logic will handle the non null scenario better. – ManoDestra Mar 18 '16 at 17:52
  • @hatchet - The question you posted isn't helpful. I guess the answer below by user497745 is working out for me. – Shiv Mar 18 '16 at 17:52

5 Answers5

1

Assuming that you really meant to check for null rather than null or empty (according to your console comment), I'd implement the following method...

private bool checkEqualityWithTrim(string string1, string string2)
{
    bool bothNull = string1 == null && string2 == null;
    bool bothNonNullAndEqualTrimmed = string1 != null && string2 != null && string1.Trim() == string2.Trim();

    return bothNull || bothNonNullAndEqualTrimmed;
}

Then you can just do...

var areEqual = checkEqualityWithTrim(string1, string2);

If the IsNullOrEmpty() was intentional, then just replace the bothNull line with

bool bothNull = string.IsNullOrEmpty(string1) && string.IsNullOrEmpty(string2);
ManoDestra
  • 6,325
  • 6
  • 26
  • 50
  • what if string1 is null and string2 is empty? – Iłya Bursov Mar 18 '16 at 18:07
  • I asked for clarification of that from the OP. He's using IsNullOrEmpty in his checks, but his console output suggests that he wanted to check for both being null only. I've included an alternative, just in case it was not in error. – ManoDestra Mar 18 '16 at 18:10
  • bool bothNull = string.IsNullOrWhiteSpace(string1) && string.IsNullOrWhiteSpace(string2); - is best along with the logic you posted. – Shiv Mar 18 '16 at 19:09
  • You should probably update your question, in that instance, to reflect this. This line: `Console.WriteLine("Both the string Null & equal");` They're not necessarily both null by your preceding logic. One could be null, the other could be an empty string and they'd be treated as equal. The Console output makes that a tad confusing. Glad I could be of assistance :) – ManoDestra Mar 18 '16 at 19:13
0

Yeah, you're doing more checks than you need to do. If the strings are equal, you only need to check that one of the strings is null or whitespace. If so, you know the value in both strings. This works assuming that for you NULL and whitespace are equivalent.

public static void Main(string[] args)
{
    string string1 = ""; // it can be NULL and any word too
    string string2 = ""; // it can be NULL and any word too

    if (String.Equals((string1 ?? "").Trim(), (string2 ?? "").Trim(),StringComparison.OrdinalIgnoreCase))
    {
        if (string.IsNullOrEmpty(string1)) //since the strings are equal, check one of the strings
        {
            Console.WriteLine("Both strings are null or empty & equal");
        }
        else
        {
            Console.WriteLine("Both strings have values & are equal");
        }
    }
}
Ayo I
  • 7,722
  • 5
  • 30
  • 40
0

you are looking for simple and maintainable code not efficiency...

i would code it like that:

(edited: now with all possible conditions)

{

        String string1 = "";
        String string2 = "";

        if (String.IsNullOrEmpty(string1.Trim()) && String.IsNullOrEmpty(string2.Trim()))
        {
            Console.WriteLine("Both the string Null & equal");
        }
        else if (!String.IsNullOrEmpty(string1.Trim()) && String.IsNullOrEmpty(string2.Trim()))
        {
            Console.WriteLine("String2 is null and string1 is not!");
        }

        else if (String.IsNullOrEmpty(string1.Trim()) && !String.IsNullOrEmpty(string2.Trim()))
        {
            Console.WriteLine("String1 is null and string2 is not!");
        }
        else {

            if (string1.Trim().Equals( string2.Trim())) {
                Console.WriteLine("both strings are not null and Equals!");
            }
            else {
                Console.WriteLine("both strings are not null! and not Equals");
            }  
        }
    }
Jonathan Applebaum
  • 5,738
  • 4
  • 33
  • 52
0

If you can use C# 6 I would definitely suggest you to use the Null Conditional Operator (called also the Elvis operator):

var test = "";
var test2 = "";

if (String.IsNullOrEmpty(test?.Trim()) && String.IsNullOrEmpty(test2?.Trim()))
{
    Console.WriteLine("both strings are null or empty and equal");
}
else
{
    Console.WriteLine("both strings have value and are equal");
}

Also depending on what the string " " (space) means for you (empty or value) use IsNullOrEmpty (in the case of value) or IsNullOrWhitespace (in the case of empty).

David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
0

Here is my attempt for you.

If this is something that is going to be used a lot then maybe using extension methods may be the way to go.

I have created two extension methods for you.

1 that performs a null and whitespace check (both conditions will be treated as a null

the second performs the logic you are after.

Here is my attempt for you:

 public static bool IsNull(this string source)
            {
                return string.IsNullOrWhiteSpace(source);
            }

 public static string IsNullOrSame(this string source, string comparer)
        {
            //check for both values are null 
            if (source.IsNull() && comparer.IsNull())
            {
                return "Both Values Null or contain whitespace only";
            }

            //check if string 1 is null and string two has a value.
            if (source.IsNull() && !comparer.IsNull())
            {
                return "I don't have a Value, but string 2 does";
            }

            //check if string 1 has a value and string two is null 
            if (!source.IsNull() && comparer.IsNull())
            {
                return "I have Value, but string 2 doesn't";
            }

            //if we make it this far then both have a value,  check if the string value matches
            if(source.Trim().Equals(comparer.Trim(), StringComparison.OrdinalIgnoreCase))
            {
                return "Both value match"; 
            }

            //if values don't match
            return "strings both have values but don't match";
        }

Once you have included these extension methods into your project you can do something simple like:

var string1 = "some value"; 
var string2 = null;
var result = string1.IsNullOrSame(string2); 
Console.WriteLine(result);

this would then result in the message "I have Value, but string 2 doesn't"

The reason for the multiple return statements is one purely for readability. If we meet a "condition" then there is no point performing any more checking and the nesting of multiple if's can get a bit tiresome to debug.

Hopefully this gives you the desired functionality you are after and efficiency.

David Shorthose
  • 4,489
  • 2
  • 13
  • 12