Tricky if statement - c#

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.

Related

Why .NET executes code on false IF statement?

I have following code:
var dateFrom = DateTime.Parse(string.Format(string.Format("01.04.{0}", dateProperty.Value.AddYears(-1).Year))
if (object.nullablebool.HasValue ? object.nullablebool.Value : false
&& (string == "V" || string == "N")
&& someDate.HasValue && object.SomeOtherDate.HasValue
&& someDate.Value.Date > dateFrom.Date)
{
>> Code
}
I have tested adding .Date or even specifiing exact year from the DateTime struct, but nothing worked.
When executing the code, even if
someDate.Value.Date > dateFrom.Date
equals 1700 > 2018, the code executed as if it was true, even though the debugger says it´s false.
When I removed this part from the condition, following code:
someDate.HasValue && object.SomeOtherDate.HasValue
When I made someDate null, so someDate.HasValue is false, the if statement still executes as true.
What did it fix? Taking these two conditions to another if:
var dateFrom = DateTime.Parse(string.Format(string.Format("01.04.{0}", dateProperty.Value.AddYears(-1).Year))
if (object.nullablebool.HasValue ? object.nullablebool.Value : false
&& (string == "V" || string == "N"))
{
if (someDate.HasValue && object.SomeOtherDate.HasValue
&& someDate.Value.Date > dateFrom.Date)
{
>> Code
}
else
{
>> Code
}
}
The code works, but it´s way too ugly. I'm running on Visual Studio 2017 Pro.
Any ideas why it behaves like that? Executing false statements?
Thanks
Your if statement performs different then expected, because it is parsed different as you wouls expect.
object.nullablebool.HasValue ? object.nullablebool.Value : false && ... is parsed as object.nullablebool.HasValue ? object.nullablebool.Value : (false && ...). So if object.nullablebool has a value, thats the result of the condition. To fix this you have to add parenthesis like this:
if ((object.nullablebool.HasValue ? object.nullablebool.Value : false )
&& (string == "V" || string == "N")
&& someDate.HasValue && object.SomeOtherDate.HasValue
&& someDate.Value.Date > dateFrom.Date)
{
// if body
}
Let's brush up your code (please, get rid of names like string, object; change them into meanful names):
// You don't want any formatting but a simple constructor
var dateFrom = new DateTime(dateProperty.Value.Year - 1, 4, 1);
// object.nullablebool == true - if object.nullablebool has value and the value is true
if (object.nullablebool == true && (string == "V" || string == "N")) {
// if someDate.Value is null the result will be false
// All we have to do is to propagate the null: ?. in someDate?.Date
if (someDate?.Date > dateFrom.Date && object.SomeOtherDate.HasValue) {
// Code
}
else {
// Code
}
}

How to write shorthand if-statement with multiple conditions

For example i want to write:
txt1.Text=="A" || txt2.Text="A" ? return true : return false
I know how to work with one condition but with two i don't know.
The txt2.Text="A" instead of txt2.Text=="A" it's not what i meant.
My question was how do i add a condition to this specific if.
Yes, i know how to use in if.
the regular way to use in the other if is:
txt1.Text=="A"? return true: return false
and i want to improve that.
The code that i have written doesn't work.
Thank you
Are you looking for
return txt1.Text == "A" || txt2.Text == "A";
?
I think this is what you are looking for.
if(txt1.Text == "A" || txt2.Text == "A") //checks if txt1 is A OR txt2 is A
{
return true;
}
else
{
return false;
}

Elegant way to check whether two Strings are different

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 )))
{}

comparing dates in c# taking null value into account

I am new to c#. I am comparing two dates where one is entered by user and the other one is sytem date time. i have the code working as it stands where the obstacle has occured is how to cater for null values. the basic code I have is:
if (mydate.ToShortDateString() != TodaysDate.ToShortDateString())
{
//Error Messaage
}
else
{
//do some code
}
Any feedback will be appreciated
Why are you converting them to strings? Why not just compare the date portions of them as in date1.Date != date2.Date.
You can declare mydate as DateTime?, then it can hold null values.
As to how to handle the error, it depends on whether having a null value for mydate is considered an error or not. If it's an error, you could do:
if (mydate == null || mydate.ToShortDateString() != TodaysDate.ToShortDateString()) {
// error
}
If it's not an error condition, you could do:
if (mydate != null && mydate.ToShortDateString() != TodaysDate.ToShortDateString()) {
// error
}
If you don't declare mydate as DateTime? but instead just declare it as DateTime, then you can check for DateTime.MinValue, like this (DateTime.MinValue is the default value for a DateTime variable):
if (mydate == DateTime.MinValue || mydate.ToShortDateString() != TodaysDate.ToShortDateString()) {
// error
}
Use the ?? operator:
if ((mydate??DateTime.MinValue).ToShortDateString() != TodaysDate.ToShortDateString())
{
//Error Messaage
}
else
{
//do some code
}

C# if (strValue == "FALSE" | strValue == "TRUE")

I have a string that contains a value of either TRUE or FALSE or null, this value is read from a text file which is outside of my control. What is the best way to use '|' with 'if'? Keeping in mind strValue could also be null, if strValue is null then I don't want to enter the if statement.
if (strValue == "FALSE" | strValue == "TRUE")
{
//do stuff
}
Thanks
if (strValue == "FALSE" || strValue == "TRUE") {
// ...
}
to benefit from short circuiting. The second expression will not be tried if the first evaluates to true.
If you need case-insensitive comparisons:
if ("FALSE".Equals(strValue, StringComparison.InvariantCultureIgnoreCase) ||
"TRUE".Equals(strValue, StringComparison.InvariantCultureIgnoreCase)) {
// ...
}
Note that calling .ToUpper() or .ToLower() on null will throw NullReferenceException.
From your question, it sounds like all you REALLY care about is that the string is NOT NULL. You then have two options:
if (!string.IsNullOrEmpty(strValue))
{
//Do stuff with "TRUE" or "FALSE"
}
or, if you know it will NEVER be an empty string (""):
if (strValue != null)
{
//Do stuff with "TRUE" or "FALSE"
}
I would recommend the first choice.
I would seriously consider using ToUpper if it's out of your control - you never know when someone changes it to "True" or "true".
if (strValue.ToUpper() == "FALSE" || strValue.ToUpper() == "TRUE") {
}
Regarding the responses about ToUpper and unnecessary defensive programming:
The original question said "read from a text file which is outside of my control", and "TRUE or FALSE or null". As far as I know there is no universal way of indicating NULL in text files. In CSV files, you could treat ,, as NULL or "" (empty string). In fixed width text files, you could treat all spaces as NULL, "" or "<some spaces>", for example.
So the OP has already done some data conversion/interpretation to get to this point.
Or perhaps:
if (strValue == "FALSE") {
// do stuff
} else if (strValue == "TRUE") {
// do other stuff
} else {
// strValue was NULL or invalid.
}
Depending on your needs.
You can put all of them into a single if statement:
if (!string.IsNullOrEmpty(strValue) && (strValue == "TRUE" || strValue == "FALSE")
{
//do stuff
}
The first condition will be evaluated first, and then the others afterwards. I prefer to have the explicit null check, to help other probably less experienced developer to understand the code.
if strValue is null then I don't want to enter the if statement
If that really is the case then why are you worried about the "|" (bitwise or) operator.
You could just write:
if (strValue != "NULL")
{
}
What you probably mean is to use the (logical or) operator "||" on the true or false values.
if (strValue == "TRUE" || strValue == "FALSE")
{
}
I could keep guessing on the scenarios but I'm sure you get the gist of it.
Since there are only three options "TRUE", "FALSE", "null", I recommend using the following:
if(String.Compare(strValue, "null") != 0){
//do stuff
}
If you need a maximum compatibility and cannot rely on your input, you could switch strValue with strValue.toLower().

Categories

Resources