How does C# evaluate Logic block? - c#

I have the following line of code:
public bool dcpl_radar()
{
if (radar == null)
return false;
else
{
if (radar != null)
{
if (radar.InvokeRequired)
radar.BeginInvoke(new MethodInvoker(delegate()
{
radar.Visible = false;
}));
else
this.radar.Visible = false;
radar = null;
}
return true;
}//end of else statement
}
but VStudio keeps throwing an error on the invoke line. I've checked the Debugger and if (radar == null) is true, yet VStudio is trying to evaluate a part of the code it shouldn't be in. Can someone explain why it's doing this please?

Wait a minute... I think we have a race condition.
Lets say you BeginInvoke, almost immediately you set radar = null.
There really is no telling when your anonymous delegate will be executed.
I would imagine this should solve your issue.
public bool dcpl_radar()
{
if (radar != null)
{
if (radar.InvokeRequired)
{
radar.BeginInvoke(new MethodInvoker(HideRadar));
}
else
{
HideRadar();
}
return true;
}
return false;
}
private void HideRadar()
{
this.radar.Visible = false;
this.radar = null;
}

What is happening:
The anonymous delegate is being called after you set the radar to null.
How to fix it
public bool dcpl_radar()
{
if (radar == null)
return false;
else
{
if (radar != null)
{
if (radar.InvokeRequired)
radar.BeginInvoke(new MethodInvoker(delegate()
{
radar.Visible = false;
radar = null;
}));
else {
this.radar.Visible = false;
radar = null;
}
}
return true;
}//end of else statement
}
(Note where I've moved your 'null' assignments).
Though I am a bit worried about the point of setting a variable to null, it's generally a sign of a bad design.

Related

How to handle NoNullAllowedException in try/catch?

I have a form in C# for inputting some data into a List.
The form consists of text boxes and up and down numeric boxes. Everything works fine but I want to have an error handler (try/catch) in my code so it will check if any of the text boxes are empty or the numeric boxes are left to 0, if thats the case it should pop up an error message.
I tried :
try
{
//code
}
catch (NoNullAllowedException e) //tried it without the e as well
{
//code
}
The code I was having in the brackets its the following one. Sometimes the GetItemDetails() was throwing me an error saying that not all code paths returns a value.
Any thoughts why is doing this or how can I fix it?
public iRepairable GetItemDetails()
{
Shirt shirt = null;
TShirt tshirt = null;
Trouser trouser = null;
Shoe shoe = null;
Boolean isShirt = true;
Boolean isTshirt = true;
Boolean isTrouser = true;
Boolean isShoe = true;
if (rdoShirt.Checked == true)
{
shirt = new Shirt(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);
isTshirt = false;
isTrouser = false;
isShoe = false;
}
else if (rdoTShirt.Checked == true)
{
tshirt = new TShirt(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);
isShirt = false;
isTrouser = false;
isShoe = false;
}
else if (rdoTrouser.Checked == true)
{
trouser = new Trouser(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);
isShirt = false;
isTshirt = false;
isShoe = false;
}
else
{
shoe = new Shoe(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);
isShirt = false;
isTrouser = false;
isTshirt = false;
}
if (isShirt)
{
return shirt;
}
else if (isTshirt)
{
return tshirt;
}
else if (isTrouser)
{
return trouser;
}
else //if(isShoe)
{
return shoe;
}
First of all, the NoNullAllowedException is not for list or just null values. Is the exception that throws when you want to insert null values in a column that doesn't allow them (for more info, MSDN).
For your code, place at the bottom of your code a default return value (but as far as i can see, your code shouldnt break at all)

Why my C# code is causing a Stack Overflow

This is the code giving a stack overflow it only happens about half the time and i have no idea why it's doing it. From what I seen it only happens with the Coms(TopCom, etc) are in a mass of numbers so around 5+ then it stack overflows.
public bool getConnected(int d) {
if (topCom.connection != null) {
if (d != topCom.connection.id) {
if (topCom.connection.id == 0) {
return true;
} else if (topCom.connection.connected == true) {
if (Development.instance.currentDos.buttons[topCom.connection.id].getConnected(id)) {
return true;
}
}
}
}
if (leftCom.connection != null) {
if (d != leftCom.connection.id) {
if (leftCom.connection.id == 0) {
return true;
} else if (leftCom.connection.connected == true) {
if (Development.instance.currentDos.buttons[leftCom.connection.id].getConnected(id)) {
return true;
}
}
}
}
if (rightCom.connection != null) {
if (d != rightCom.connection.id) {
if (rightCom.connection.id == 0) {
return true;
} else if (rightCom.connection.connected == true) {
if (Development.instance.currentDos.buttons[rightCom.connection.id].getConnected(id)) {
return true;
}
}
}
}
if (botCom.connection != null) {
if (d != botCom.connection.id) {
if (botCom.connection.id == 0) {
return true;
} else if (botCom.connection.connected == true) {
if (Development.instance.currentDos.buttons[botCom.connection.id].getConnected(id)) {
return true;
}
}
}
}
return false;
}
This happens in recursive functions where you don't have a base condition for ending the recursion. You basically keep calling the function until you reach stack overflow.. Trace your code through and figure out why it calls itself endlessly.
The fact that people here can't really tell what you're trying to accomplish is a code smell of sorts.
A big part of that is the fact that you have an incredible amount of nesting in your code. Nested conditionals increase the difficulty of debugging code, as you're discovering now. Additionally, you could easily combine some of your conditionals - all of your conditionals in any top-level branch can actually be combined into one statement, as follows:
if ((topCom.connection != null && d != topCom.connection.id && topCom.connection.id == 0) ||
(topCom.connection.connected == true &&
Development.instance.currentDos.buttons[topCom.connection.id].getConnected(id)))
{
return true;
}
return false;
As far as I can imagine, there's no point in having separate conditional branches that perform the same function, e.g. if (a) { return true; } else if (b) { return true; }. Just move the logic from else if into the original if conditional.
However, I'd recommend encapsulating some or all of this logic into a separate function, given that it seems like you're performing the same logic on each of your connections. You could create a function like so:
public bool ConnectionIsValid(connectionObject // replace with the actual type)
{
if (topCom.connection != null && d != topCom.connection.id && topCom.connection.id == 0)
|| (topCom.connection.connected == true
&& Development.instance.currentDos.buttons[topCom.connection.id].getConnected(id))
return true;
return false;
}
So that you could then just call ConnectionIsValid on each of your connections, rather than using 80-some lines on conditionals for each connection.
It also seems doubtful that there's a StackOverflowException occurring in this code. Unless you have a circular reference related to any of the objects referenced in this code (in which case, there's a decent chance you used a setter accessor to assign a value to the same variable:
object A
{
set
{
this.A = value;
}
}
which will always cause a stack overflow, it's likely you've introduced some sort of recursion outside the scope of the included code.

NullReferenceException was unhandled

I'm just getting the hang of Lightswitch, but I keep getting the null reference exception error when I'm trying to find out if a selected item in a datagrid contains the letters "CMP". I look all over the place but I think I'm doing something wrong. Here is my code for reference:
if(string.IsNullOrWhiteSpace(this.location.SelectedItem.locationID))
{
this.ShowMessageBox("test"); //not sure what to put there so I just made something up
}
else if (this.location.SelectedItem.locationID.Contains("CMP"))
{
this.FindControl("datePurchased").IsVisible = true;
this.FindControl("age").IsVisible = true;
this.FindControl("userList").IsVisible = true;
}
else
{
this.FindControl("datePurchased").IsVisible = false;
this.FindControl("age").IsVisible = false;
this.FindControl("userList").IsVisible = false;
}
I also tried
if(this.location.selecteditem.locationID != null)
if(string.IsNullOrEmpty)
but it always throws me the same error. Any help would be much appreciated!
I guss this.location or this.location.selecteditem may be null, So you got that error.
So please try this if condition instead of your if condition way
if(this.location != null && this.location.selecteditem !=null && this.location.selecteditem.locationID != null)
{
//Write your code here
}
So your final code look like
if(this.location == null && this.location.selecteditem ==null && this.location.selecteditem.locationID == null)
{
this.ShowMessageBox("test"); //not sure what to put there so I just made something up
}
else if (this.location.SelectedItem.locationID.Contains("CMP"))
{
this.FindControl("datePurchased").IsVisible = true;
this.FindControl("age").IsVisible = true;
this.FindControl("userList").IsVisible = true;
}
else
{
this.FindControl("datePurchased").IsVisible = false;
this.FindControl("age").IsVisible = false;
this.FindControl("userList").IsVisible = false;
}

Need help to refactor the nested if else statements

Please find the following code and help me write a better if...else code. I feel this is a very below average way to write else if.
{
Retrieve the number in focus.
string number= getnumber();
string zipcode;
int corporate;
bool bCoverageInBet = false;
try
{
//Get the address and zipcode of the number
GetAddress(number, out address);
if (adress!= null)
{
zipcode = adress.zipcode
//if the following are null means this is first time call
if (!(string.IsNullOrEmpty(_loadedZipcode)) && _address != null)
{
if (zipcode.Equals(_loadedZipcode))
{
if (adress.Equals(_address ))
{
if (focusChanged)
{
return result;
}
}
else
{
if (bCoverageInBet)
{
// case 2: Different address and different coverage which is in between, make a call anf get new valus for result
//return the new result
}
else
{
return //current result value;
}
}
}
}
else
{
_loadedZipcode = zipcode;
_address = adress;
GetResponse( out resp)
{
if ((resp != null))
{
bool isCorporate = false;
corporate = getValues();
if (corporate .Equals(100))
{
result = true;
return result;
}
else if (corporate > 0 && corporate < 100)
{
//Make a call to get corporate
bCoverageInBet = true;
LocationResponse objResults;
if (GetAddressbycorporate(out objResults, out errMsg))
{
if (objResults != null)
{
isCorporate = objResults.located;
if (isCorporate )
{
result = true;
}
}
}
}
return result;
}
return result;
}
else
{
DisplayError("No response ");
return result;
}
}
}
else
{
//To do: What is address comes null
}
}
catch (System.Exception ex)
{
//some ccode
}
return result;
}
Thanks
K
Refactor the method into smaller units as appropriate. Also, return early from the method rather than using else clauses.
E.g. instead of
if (adress!= null)
{
zipcode = adress.zipcode
//if the following are null means this is first time call
if (!(string.IsNullOrEmpty(_loadedZipcode)) && _address != null)
{
}
else
{
return false;
}
}
else
{
return false;
}
Do:
if (adress == null)
{
return false;
}
if (string.IsNullOrEmpty(_loadedZipcode) || _address == null)
{
return false;
}
There are quite a few other problems, but that should make the code cleaner to start with.
I don't think anyone is going to "help" you rewrite this code. However, I can offer some suggestions.
I have found it easier to trace my way down to the inner most if and try to rewrite and work my way backwards (up the chain). Depending on the IF block, it is sometimes easier to break them out into separate methods where appropriate.
Also, don't forget about the conditional operator. It can sometimes be clearer to use that than a whole if else block.
For example, property = (boolean expression) ? (true value) : (false value);
Here is a link to MSDN on it: conditonal operator documentation

Null Reference in editing a task scheduler trigger in c#

if (t != null) is always null why help..
when ever i try to get value in the variable name t it always gets in the else part but i am sure that there is valuse in tat variable.
private void button3_Click(object sender, EventArgs e)
{
try
{
if (search=="")
{
}
else
{
if (textBox1.Text=="")
{
MessageBox.Show("Select A Task Or Find One");
}
else
{
search = textBox1.Text;
}
}
if (search != null)
{
t = tasks.OpenTask(search);
if (textBox2.Text!="")
{
short hour = short.Parse(textBox2.Text.Substring(0, 2));
short minute = short.Parse(textBox2.Text.Substring(3, 2));
if (t != null) // this is null dont know why
{
foreach (Trigger tr in t.Triggers)
{
if (tr is StartableTrigger)
{
(tr as StartableTrigger).StartHour = hour;
(tr as StartableTrigger).StartMinute = minute;
}
}
t.Save();
t.Close();
}
tasks.Dispose();
button2.Visible = true;
textBox3.Visible = true;
search = "";
}
else
{
MessageBox.Show("Enter Time ");
}
}
}
catch (Exception b)
{
MessageBox.Show(b.ToString());
// MessageBox.Show("Select A Task From The List ");
}
}
help guys .. well i tried it to debug but didnt get a break through..
t is null because tasks.OpenTask(search) returns null.
Probably there is no task matching your search criteria.
Why are you disposing of tasks in the first place?
Any place in your source ,where you have written something like this MyClass t = new MyClass().. where t is your class object. If you have not declared,It will always come null.
Or might be you have declared something like this
private Task t; but forgot to add new keyword. Checkout!!!

Categories