I have a object with type:
dynamic {System.DBNull}
I want to check it:
if (myObject!= null || myObject!= DBNull.Value)
{
MessageBox.Show("Oh hi");
}
But the MessageBox always appears. Whats wrong, is it another type?
This expression is always true
myObject != null || myObject != DBNull.Value
because myObject cannot be null and DBNull.Value at the same time. Replace || with && to fix.
Try this code
if(myObject != DBNull.Value)
{
MessageBox.Show("Oh hi");
}
or
if(myObject != null && myObject != DBNull.Value)
{
MessageBox.Show("Oh hi");
}
There is also a function for checking for DBNull:
if(myObject != null && !Convert.IsDBNull(myObject))
{
MessageBox.Show("Oh hi");
}
Related
When the check against the emailaddress is added to the if statement, as per below, the if statement if (origin.Equals(true)).
bool origin = false;
Contact contact = item as Contact;
foreach (Item subItem in contactItems)
{
Contact subcontact = subItem as Contact;
if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null)) && ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName)) && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))))
{
if (origin.Equals(true))
{
try
{
Console.WriteLine(contact.DisplayName + " " + subcontact.DisplayName);
Console.WriteLine(contact.EmailAddresses[EmailAddressKey.EmailAddress1]);
subcontact.Delete(DeleteMode.HardDelete);
}
catch
{
Console.WriteLine("Cannot delete" + " " + subcontact.DisplayName);
}
}
origin = true;
}
}
If I remove the if (origin.Equals(true)) or removed && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])) from the other if statement, the contact goes through the try-catch block.
Can anyone see why?
if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null)) && ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName)) && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))))
should be:
if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null)
&& ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName))
&& ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))
the problem as I can see, is in the amount of ( ) you use, which I believe is incorrect.
Try to clean up your if statements to prevent these types of mistakes from happening, since this one was pretty long, and a few of your parenthesis are unnecessary
EDIT:
I tried running some code and it works. I did make some mistakes in the sample of the IF statement I mentioned above.. Maybe try copying my code, and substituting your specific code into it. It should work this way.
public static void Main()
{
bool origin = false;
int[] t = {0,4,6,8,5,6,4,5};
foreach(int i in t){
if ((true || (true && true)) // if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null))
&& ((true && true) || (true)) // && ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName)))
&& ((true && true) || (true))) // && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))))
{
if (origin.Equals(true))
{
try
{
Console.WriteLine("here");
}
catch
{
Console.WriteLine("Cannot delete" );
}
}
origin = true;
}
}
}
I suggest a little Helper:
private bool EqualOrBothNull( string fromContact, string fromSubcontact )
{
if ( fromContact == null && fromSubcontact == null ) return true;
if ( fromContact != null && fromContact.Equals(fromSubcontact) ) return true;
return false;
}
then you can use it like this:
if ( EqualOrBothNull( contact.DisplayName, subContact.DisplayName ) &&
EqualOrBothNull( contact.CompanyName, subContact.CompanyName ) &&
EqualOrBothNull( contact.EmailAddresses[EmailAddressKey.EmailAddress1],
subContact.EmailAddresses[EmailAddressKey.EmailAddress1])
)
{
// ...
}
This increases readability and will make it easier to find the bug if any.
Thanks for all the potential answers unfortunately they didn't fix the issue, the code is much easier to read though! In the end I separated the email address check to another IF statement which seems to be working
I have an IF statement that is supposed to make sure the TextBox1.Text and TextBox2.Text do not match or are not blank. If they don't match or are not blank then it is supposed to assign the text in the boxes to two string variable. What I can't figure out is why when I leave the two textboxes blank the true statement still fires.
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text == "" && tbEndBreak2.Text == ""))
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
There are two conditions in your if statement:
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text == "" && tbEndBreak2.Text == ""))
The first one checks to make sure they don't match (so, good). The second checks to make sure that they are blank (so, bad). You want this:
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text != "" && tbEndBreak2.Text != ""))
Also, what are you trying to do? The second condition is the only one you need if you really want them not to match OR not be blank - because the only time this will be false is if they are both blank.
You wrote "OR textbox are blank", you need "OR textbox are not blank"
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text != "" && tbEndBreak2.Text != ""))
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
As a side note, I'd replace "" with string.Empty for readability.
if ((tbStartBreak2.Text != tbEndBreak2.Text) || (tbStartBreak2.Text != string.Empty && tbEndBreak2.Text != string.Empty))
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
And for even more readability, you can extract these big conditions
if (TextboxesDoNotMatch() || TextboxesAreNotEmpty())
{
sb2 = tbStartBreak2.Text;
se2 = tbStartBreak2.Text;
}
private bool TextboxesDoNotMatch()
{
return tbStartBreak2.Text != tbEndBreak2.Text;
}
private bool TextboxesAreNotEmpty()
{
return tbStartBreak2.Text != string.Empty && tbEndBreak2.Text != string.Empty;
}
If you want it to return that they are NOT blank then you need to do this
(tbStartBreak2.Text != "" && tbEndBreak2.Text != "")
you have an OR between both conditions so when both are empty the second part will be true regardless the first part
(tbStartBreak2.Text == "" && tbEndBreak2.Text == "")
I want to check that a property on an array which is itself a child object is not null.
So i have
if (Parent.Child != null && Parent.Child[0] != null && Parent.Child[0].name != null)
var myName = Parent.Child[0].name
This seems like a very long winded way to get to the child[0].name whilst avoiding null reference exceptions. I am also getting index out of range errors. Is there a better way?
If you're getting IndexOutOfRangeException errors, that suggests that Parent.Child could be empty. So really you want:
if (Parent.Child != null && Parent.Child.Count > 0 && Parent.Child[0] != null &&
Parent.Child[0].name != null)
{
...
}
There's nothing that would simplify this very much, although you could write a version of LINQ's FirstOrDefault method which even coped with the source being null:
public static T NullSafeFirstOrDefault(this IEnumerable<T> source)
{
return source == null ? default(T) : source.FirstOrDefault();
}
Then:
var firstChild = Parent.Child.NullSafeFirstOrDefault();
if (firstChild != null && firstChild.name != null)
{
...
}
Your code appears OK apart from missing a test for the array being empty and is the correct defensive programming. You should extract this into a method to make it's intention clearer and your code here cleaner:
if (Parent.HasChild())
{
var myName = Parent.Child[0].name;
}
public bool HasChild()
{
return this.Child != null && this.Child.Count > 0 &&
this.Child[0] != null && this.Child[0].name != null;
}
The only other way would be to wrap the code in a try/catch block:
try
{
var myName = Parent.Child[0].name;
...
}
catch
{
}
However, this is bad programming practice as:
You are using exceptions to control program flow.
You are hiding other potentially serious errors.
try
var Names = new List<string>();
if(Parent.Child != null && Parent.Child.Count() > 0){
foreach(var item in Parent.Child) Names.Add(item.name)
}
var ParentChild= Parent.Child[0] ;
if (Parent.Child != null && ParentChild != null &&ParentChild.name != null)
var myName = ParentChild.name
Maybe simple try/catch will help?
var myName;
try
{
myName = Parent.Child[0].name;
}
catch (NullReferenceException)
{ myName = null; }
I have this long loop of if..else. Can anybody help me in knowing if "switch case" is better for this or "if..else"?
if (meals == null)
{
bfast.Hide();
lunch_rb.Hide();
dinner_rb.Hide();
}
else if (meals != null)
{
if (breakfast != null && lunch == null && dinner == null)
{
lunch_rb.Hide();
dinner_rb.Hide();
}
if (breakfast == null && lunch != null && dinner == null)
{
bfast.Hide();
dinner_rb.Hide();
}
if (breakfast == null && lunch == null && dinner != null)
{
bfast.Hide();
lunch_rb.Hide();
}
if (breakfast != null && lunch != null && dinner == null)
{
dinner_rb.Hide();
}
if (breakfast != null && lunch == null && dinner != null)
{
lunch_rb.Hide();
}
if (lunch != null && breakfast == null && dinner != null)
{
bfast.Hide();
}
I am developing an application for windows CE 5.0 (if this helps)
I think the better solution in this case is:
if (breakfast == null)
bfast.Hide();
if (lunch == null)
lunch_rb.Hide();
if (dinner == null)
dinner_rb.Hide();
You can try something like this, As you have condition on multiple variables you will need to make expression for passing it to switch so using if as given below might make it simple.
if (breakfast == null)
bfast.Hide();
if (lunch == null)
lunch_rb.Hide();
if (dinner == null)
dinner_rb.Hide();
For this particular scenario if-else is better because you have complex conditions and that's something switch-case can't do I believe.
For this question, I think if...else is good enough. switch...case cannot deal with such a complicated situation. Feel free to use it.
Switch case is always better than if...else if because it needs less typing and your codes will be easier to read and understand.I myself just use "else if" when I forget switch's style in exam's!!!
The performance level between if and switch statements is not much difference. Anyway your code is a mess of conditions. Take into consideration the answer of Pigueiras. Something like
bfast.Hide();
lunch_rb.Hide();
dinner_rb.Hide();
if (meals != null) {
if (breakfast != null)
bfast.Show();
if (lunch =! null)
lunch_rb.Show();
if (dinner =! null)
dinner_rb.Show();
}
What would be the best way to determine if an object equals number zero (0) or string.empty in C#?
EDIT: The object can equal any built-in System.Value type or reference type.
Source Code:
public void MyMethod(object input1, object input2)
{
bool result = false;
object compare = new object();
if(input != null && input2 != null)
{
if(input1 is IComparable && input2 is IComparable)
{
//do check for zero or string.empty
//if input1 equals to zero or string.empty
result = object.Equals(input2);
//if input1 not equals to zero or string.empty
result = object.Equals(input1) && object.Equals(input2); //yes not valid, but this is what I want to accomplish
}
}
}
Using Jonathan Holland code sample with a minor modification, here is the solution that worked:
static bool IsZeroOrEmpty(object o1)
{
bool Passed = false;
object ZeroValue = 0;
if(o1 != null)
{
if(o1.GetType().IsValueType)
{
Passed = (o1 as System.ValueType).Equals(Convert.ChangeType(ZeroValue, o1.GetType()))
}
else
{
if (o1.GetType() == typeof(String))
{
Passed = o1.Equals(String.Empty);
}
}
}
return Passed;
}
What's wrong with this?
public static bool IsZeroOrEmptyString(object obj)
{
if (obj == null)
return false;
else if (obj.Equals(0) || obj.Equals(""))
return true;
else
return false;
}
Michael, you need to provide a little bit more information here.
strings can be compared to null or string.Empty by using the method
string x = "Some String"
if( string.IsNullOrEmpty(string input) ) { ... }
int, decimals, doubles (and other numeric value-types) can be compared to 0 (zero) with a simple == test
int x = 0;
if(x == 0) { ... }
You can also have nullable value-types also by using the ? operator when you instantiate them. This allows you to set a value type as null.
int? x = null;
if( !x.HasValue ) { }
For any other object, a simple == null test will tell you if its null or not
object o = new object();
if( o != null ) { ... }
Hope that sheds some light on things.
Not quite sure the reasoning behind this, because .Equals is reference equality on reference types, and value equality on value types.
This seems to work, but I doubt its what you want:
static bool IsZeroOrEmpty(object o1)
{
if (o1 == null)
return false;
if (o1.GetType().IsValueType)
{
return (o1 as System.ValueType).Equals(0);
}
else
{
if (o1.GetType() == typeof(String))
{
return o1.Equals(String.Empty);
}
return o1.Equals(0);
}
}
Do you mean null or string.empty, if you're talking about strings?
if (String.IsNullOrEmpty(obj as string)) { ... do something }
Oisin
In the first case by testing if it is null. In the second case by testing if it is string.empty (you answered your own question).
I should add that an object can never be equal to 0. An object variable can have a null reference though (in reality that means the variable has the value of 0; there is no object in this case though)
obj => obj is int && (int)obj == 0 || obj is string && (string)obj == string.Empty