Elegant way to check whether two Strings are different - c#

Is there an elegant way to compare two Strings and check whether they are different? For example in Java, I usually use something similar to this:
if (text1 != text2 || (text1 != null && !text1.equals(text2))) {
// Texts are different
}
This is something so common that I was wondering maybe there is a better way.
Edit:
Ideally I want a pseudo code applicable to most common object oriented languages.

In Java 7+, you can use Objects#equals:
if (!Objects.equals(text1, text2))
Under the hood, it does something similar to the code in your question:
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
Note that your code is broken in Java by the way: it will return false in this case:
String text1 = "abc";
String text2 = new String("abc");
if (text1 != text2 || (text1 != null && !text1.equals(text2))) {
System.out.println("Ooops, there is a bug");
}
The proper way to write a isNotEquals condition would be:
if (text1 != text2 && (text1 == null || !text1.equals(text2)))

Java (7 onwards):
Objects.equals(first, second);
C#:
string.Equals(first, second);

This (C#):
if(text1 != text2){
}
should do the trick as the == operator and the != operator are overloaded to do a proper string compare.
MSDN Reference

In c# personally i use the above
If(!string.IsNullOrEmpty(text1) || (!string.IsNullOrEmpty(text2) && (text1 != text2 )))
{}

Related

If statement clarification of AND/OR

I'm sorry to ask such an easy question.. I just need some clarifications, because sometimes I mix the differences up.
Can somebody please help me by explaining the difference between the following if statements?
sending = true;
if (sending && e.AssetType == AssetType.Notecard) //#1
vs.
if ((sending) && (e.AssetType == AssetType.Notecard)) //#2
vs.
if (sending || e.AssetType == AssetType.Notecard) //#3
vs.
if ((sending) || (e.AssetType == AssetType.Notecard)) //#4
In this specific case, I need it to evaluate to something like:
"If(sending == true AND e.AssetType == AssetType.Notecard)"
In an other case I need the if statement to check one string and contents of a list like:
"If(string == "Name" OR List.Contains("string"))
The first and the second statements are the same (parenthesis are not obligatory in this case, because of C# evaluation priorities!)
if (sending && e.AssetType == AssetType.Notecard)
if ((sending) && (e.AssetType == AssetType.Notecard))
just as:
if ((sending == true) && e.AssetType == AssetType.Notecard))
if ((sending) && (e.AssetType == AssetType.Notecard))
Also the 3° and the 4° statement will give the same result, for the same reason mentioned above: http://msdn.microsoft.com/en-us/library/6a71f45d.aspx
I would use these statements:
if (sending && (e.AssetType == AssetType.Notecard))
and:
if ((string == "Name") || List.Contains("string"))
(but please take care of string comparison modes, such as upper/lower cases and cultures:
String.Compare(string, "Name", StringComparison.CurrentCultureIgnoreCase) == 0
compares strings without regard of the case and with the current culture)
There is no any difference in those codes.
if ((sending) && (e.AssetType == AssetType.Notecard)) and if (sending && e.AssetType == AssetType.Notecard) evaluates into the same thing.
if(sending == true) or if(sending) is the same thing too.
If you're asking about difference between || and &&:
|| is a LOGICAL-OR. It's enough that only one condition would be TRUE to pass if
&& is a LOGICAL-AND. All conditions must be TRUE in order to pass if
In both cases the evaluation will be done from the left to right.
Example of sequence:
if ((sending) && (e.AssetType == AssetType.Notecard)) => if sending==true AND ..rest..
For the first and second statements produce the same result and for the third and fourth statements also produce the same result.
A couple of things to clarify:
In this case, parentheses are not required and it is just extra code.
When you use Logical-AND operation, the first part is always evaluated, and the second part will only be evaluated if the first part is true.
When you use Logical-OR operation, both parts are always evaluated.
When you have more than +2 expressions, then use parentheses to clarify your intentions. e.g. if(A && B || C) is the same as if((A && B) || C) because the Operators Precedence. but if you want the logical-OR operation to be execute first, then you must use parentheses to override the precedence if(A && (B || C))
Furthermore, if(A && B == C) is the same as if(A && (B == C)) because Equality operation has higher precedence than logical-AND

How to use AND operator logic in Or Operator i cant solve it in interview?

suppose i have a code like this,
(var1==true && var2==true)
{
somemethod();
}
suppose we have a language in which we do not have && operator it is not exsis in the language then what changing in the condition to make it like (var1==true || var2==true)
and work like and operator that when both condion true then it enter in the loop and do not use any code like using if condition for both condition to make it work
hopes for your suggestions thanks in advance
if (!(!var1 || !var2))
{
somemethod();
}
By DeMorgan's law:
a and b === !!(a and b) === !(!a or !b)
http://en.wikipedia.org/wiki/De_Morgans_laws
You can simply use the below:
(!(!var1 || !var2))
Steps below:
(var1==true && var2==true)
(var1 && var2)
!(!(var1 && var2))
!(!var1 || !var2)
Since they are booleans, you could also use '&'
if (var1 & var2) {
}
which 'could' be simpler for humans to understand, then multiple negations.
if (var1)
if (var2)
someMethod(); // var1 and var2 are both true

Tricky if statement

Is it possible to convert this if statement into a one line statement ?
if (value != DBNull.Value)
{
dic.Add(columnName);
}
else if (!skipNullValues)
{
dic.Add(columnName);
}
if (value != DBNull.Value || !skipNullValues) dic.Add(columnName);
Use a logical OR:
if (value != DBNull.Value || !skipNullValues)
dic.Add(columnName);
I would keep the addition on a new line for clarity, although for a simple statement like this you're probably alright to drop the curly brackets. You do need to be careful if you try to add more logic in the future though obviously in the branch of the if.
if (!(value == DBNull.Value && skipNullValues))
dic.Add(columnName);
If you edit to include why making it a single line will help you might get a more suitable answer. Here are a few different approaches you could take..
First off, in a single line as you requested:
if ((value != DBNull.Value) || (value == DBNull.Value && !skipNullValues)) { dic.Add(columnName); }
Alternatively you might want to look into using ternary operators if you need something more compact.
var result = (istrue) ? (return valIfTrue) : (return valIfFalse);
More info on ternary operators:
http://msdn.microsoft.com/en-us/library/ty67wk28%28v=vs.80%29.aspx
Most likely (depending on your situation) you should consider creating a method similar to this:
public void AddColumnToDic(object value, string columnName)
bool skipNullValues = false; // todo: read from configuration
if ((value != DBNull.Value) || (value == DBNull.Value && !skipNullValues))
{
dic.Add(columnName);
}
}
and simply call it for every cell value you encounter.

Compare strings in if statement

Trying to write a piece of code to compare two strings. If either are equal to the textbox then it opens a new winform. I know how to do the winform part.
string CreditCard1 = "Some numbers";
string CreditCard2 = "Some Numbers";
string RFIDCard1 = "E00700000330E44C";
string RFIDCard2 = "E00700000338E539";
if(CardScan_txtBx = CreditCard1 || RFIDCard1)`
I get an error from MSVS 2010 saying:
Operator '||' cannot be applied to operands of type 'string' and 'string'
Is there a way to do what I want?
This line is the culprit:
if(CardScan_txtBx = CreditCard1 || RFIDCard1)`
Try:
if(CardScan_txtBx.Text == CreditCard1 || CardScan_txtBx.Text == RFIDCard1)
On a side note, it scares me that you're apparently working with credit card information, but don't know how to compare values in a text box. I really, really hope, for the sake of your customers, that you plan on investigating how to securely manage that information.
There are three problems here:
You cannot compare against multiple values using an OR (||). This is a surprisingly common misconception, but makes no sense to the compiler.
Comparison in C# is done with ==. = is for assignment.
A TextBox is not a string; you need to use its Text property to get or set the text it contains.
So in the end, your if statement should look like this:
if(CardScan_txtBx.Text == CreditCard1 || CardScan_txtBx.Text == RFIDCard1) {
// ...
}
Ok you have 2 issues here, firstly single equals is assignment not comparison and secondly each argument separated by an or needs to be a bool, ie should be
if(CardScan_txtBx == CreditCard1 ||CardScan_txtBx == RFIDCard1)
Could you use else if?
if(CardScan_txtBx == CreditCard1)
{
//Do something
} else if(CardScan_txtBx == RFIDCard1)
{
//Do something
}
The other answers have the correct code, here is an explanation of the why. When you use the || operator, it is expecting an expression on either side to be something that evaluates to a bool (true or false). When you wrote CardScan_txtBx.Text == CreditCard1 || RFIDCard1 you have an statement that evaluates to a bool on the left, CardScan_txtBx.Text == CreditCard1 and you have a statement that evaluates to string on right RFIDCard1 Because a string is not a bool, you get the compile time error. that is why you must repeat the == operator on the right hand side so that you say CardScan_txtBx.Text == RFIDCard1
Try out with following code.....
if (CardScan_txtBx.Equals(CreditCard1) || CardScan_txtBx.Equals(RFIDCard1))
{
//Code
}
Try this:
if (CardScan_txtBx.Text == CreditCard1 || CardScan_txtBx.Text == RFIDCard1)
See here: http://msdn.microsoft.com/en-us/library/53k8ybth%28v=vs.71%29.aspx
Not: =
Right: expr1 == expr2
You can also use a List.
List<string> listOfValidStrings = new List<string>();
//Initialise all valid strings.
if(listOfValidStrings.contains(txtbox.text())
{ do something.}

Concat string in IsNullOrEmpty parameter

I was looking at a piece of code I wrote in C#:
if(string.IsNullOrEmpty(param1) && string.IsNullOrEmpty(param2) && string.IsNullOrEmpty(param3))
{
// do stuff
}
and decided to make it more readable/concise
if(string.IsNullOrEmpty(param1+param2+param3))
{
// do stuff
}
But looking at it I can't help but cringe. What are your thoughts on this? Have you ever done something like this and do you use it whenever applicable.
Note: The code previous to this line would manipulate a collection by adding specific items depending on if the a param (param1,param2,param3) is NOT empty. This if statement is meant for validation/error handeling.
Personally I prefer the former over the latter. To me the intent is more explicit -- checking if all parameters are null/empty.
The second also hides the fact it does handle nulls. Null strings are odd. Jason Williams above, for example, didn't relise that it does in fact work.
Maybe write it something like this, which is a bit more readable:
bool paramsAreInvalid =
string.IsNullOrEmpty(param1)
&& string.IsNullOrEmpty(param2)
&& string.IsNullOrEmpty(param3);
if (paramsAreInvalid)
{
// do stuff
}
It's a small thing, but I think a minor reformatting of your original results in improved readability and makes the intent of the code about as crystal clear as can be:
if ( string.IsNullOrEmpty(param1) &&
string.IsNullOrEmpty(param2) &&
string.IsNullOrEmpty(param3) )
{
// do stuff
}
Consider this similar set of examples:
if ( c == 's' || c == 'o' || c == 'm' || c == 'e' || c == 't' || c == 'h' || c == 'i' || c == 'n' || c == 'g') {
// ...
}
if ( c == 's' ||
c == 'o' ||
c == 'm' ||
c == 'e' ||
c == 't' ||
c == 'h' ||
c == 'i' ||
c == 'n' ||
c == 'g') {
// ...
}
That won't work. If any of the strings are null, you'll get a null dereference exception. You need to check them before you use them.
In addition, it's very inefficient. You are concatenating all the strings into a new string, then test if this is non-empty. This results in one or more memory allocations and potentially a lot of data being copied, only to be immediately thrown away and garbage collected a moment later.
A better approach is to write a method that takes variable arguments or a list of strings and checks them one by one using IsNullOrEmpty in a loop. This will be more efficient, safe, but still achieve the desired result of tidy code in your if statement.
If you can get the params in a collection (which if it's function you can with the params keyword) then this might work:
if (myParams.Any(IsNullOrTrimEmpty)
{
// do stuff
}
The example uses this string extension and myParams is a string[].
The original code, though longer, is more clear in its intent, and likely similar performance-wise. I'd leave it alone.

Categories

Resources