I'm attempting to create a function class in C# for use in an excel Automation add-in. Using the simple code below, I was wanting to add the values in a range that match the colour that the user selects (for example, sum Range("A1:A10") where the cell colour is the same as "B1" would be: colourSum(A1:A10,B1).
public double ColourSum(Range RangeToSum, Range cellContainingColourToSum)
{
double currentTotal = 0;
//return 0; this code is edited from my original posting, due to posting error
for (int i = 0; i < RangeToSum.Cells.Count;i++) //error at 'int i'
{
double iColour = RangeToSum.Interior.ColorIndex(i);
if (iColour == cellContainingColourToSum.Interior.ColorIndex)
{
currentTotal = currentTotal + RangeToSum.Value2(i);
//return currentTotal;
}
}
return currentTotal;
}
Unfortunately, the above code returns "Unreachable code detected" on line 4. The code example I've given is a simplified example of what I actually want to do but illustrates my point quite well. Is there a problem with my code, or can I write in a better way to avoid this problem?
Thanks,
Rico.
To conclude the question, the following code worked completely (changing for(int i...with foreach (Range r...):
public double ColourSum(Range RangeToSum, Range cellContainingColourToSum)
{
double currentTotal = 0;
foreach (Range r in RangeToSum)
{
double iColour = r.Interior.ColorIndex;
if (iColour == cellContainingColourToSum.Interior.ColorIndex)
{
currentTotal = currentTotal + r.Value2;
}
}
return currentTotal;
}
The minute your code hits the line:
return 0;
it will exit, there's no way for it to reach the rest of the code. Remove the line.
When the line return 0 is hit, the function ends, and nothing after that is executed. Hence, it is unreachable code. Remove this line to get the function to behave properly.
You're returning 0 before you get to the loop. Thats why the code is unreachable.
return 0;
perhaps your dll is not compiled and replaced in the output directory. You must clean-rebuild all the code. (will be good if you could delete everything manually from output folder).
If this dll is added as a project reference then delete and re-add the project reference. May be it works that way.
Related
So I am having a bit of issue with this piece of code for a class of mine. I know it seems rather elementary but for the life of me I am not sure why I can't get it to work.
Essentially I have 6 radio buttons and depending on which one is selected I want to assign a value to an int variable. I want to return that value to another winForm which will do something else.
but for some reason it always returns 0.
some help would be greatly appreciated.
Thank you in advance..
int x = 0;
public int selectionDie1()
{
if (die1_1.Checked)
x = 1;
if (die1_2.Checked)
x = 2;
if (die1_3.Checked)
x = 3;
if (die1_4.Checked)
x = 4;
if (die1_5.Checked)
x = 5;
if (die1_6.Checked)
x = 6;
return x;
}
I like to also add that even if I change this to a void with no return value and place a label that would display the value of x on buttonclick, it still returns a 0.
I have even tried using just one radiobutton and see if that would work, nothing at all.
when I set x = 1000; and return that it works fine, so it has to do with the radio buttons
thank you
If I understand this correctly, you are attempting to use the variable x in your other form. You need to use the direct result of the selectionDie1 function.
public int selectionDie1()
{
if (die1_1.Checked)
return 1;
else if (die1_2.Checked)
return 2;
...
else
throw new exception("there was no item checked");
}
This way there is no variable to keep track of, or could be accessed from an outside location.
The other issue is that you are creating a form and then immediately checking for the selected item (if your comment is correct). You need to first create and show the form, give the user time to choose an option, and then do this function call (which might happen on a user selection, form close, button press, etc).
I was looking at a code sample in C#. There is ; without any statement before it. I thought it is typo. I tried to compile with ;. It compiled fine. What is the use of ; without any code statement?
I'm using VS 2010, C# and .Net 4.0
private void CheckSmcOverride(PatLiverSmc smc)
{
;
if (smc.SmcOverride && smc.Smc != null
&& smc.Smc.Value < LiverSmcConst.SMC_OVERRIDE_POINT)
{
smc.Smc = 10;
_logger.DebugFormat("CheckSmcOverride: Override SMC {0}", smc.Smc);
}
}
A semicolon in C# is simply to denote an end-of-a-statement. Empty statements, or just a ; by itself, are valid.
You could have the following on a line by itself inside any function in C# and it should will compile fine:
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
On the same topic, but semi-different from the question at hand, is an empty set of curly-brackets, { }. These denote a "code block", but are valid just about anywhere in your code. Again, you could have something like the following on a single line and it will still compile fine:
{ } { ;;;;;;;;;; } { }
In the end, the empty-statement and empty-code blocks all compile down to "nothing to see here folks, move along" and can, in most cases, be removed from the code without consequence.
As a c# developer I use the 'empty statement'
;
(a useful case as a comment requested)
when I have a multi line lambda and I want to examine the last line of evaluation i.e.
list.ForEach(x=>
{
x.result = x.Value * x.AnotherValue;
; // otherwise I can't ever see these as you can't break on the end brace of an anonymous function
})
as a way to break point inside some code after evaluation of the line before i.e.
void SomeFunct()
{
int a = someOtherFunct();
; //I want a breakpoint here but...
//there is some huge code segment that will get skipped before I can breakpoint
}
It's a statement that does nothing. Normally this would be pointless and could just be removed, but there are times where a statement is expected and you really want nothing to happen.
Sometimes you see this with loops that cause side effects and so need no body:
int count = 0;
while(isTheRightNumber(count++))
;
Personally I dislike such code examples and discourage the practice as they tend to be harder to understand than loops that have side effect free conditions. Using a set of empty braces is a bit clearer, as is including a relevant comment, such as:
int count = 0;
while(isTheRightNumber(count++))
{ } //empty by design
Another example is the pattern of using a for loop for an infinite loop:
for(;;)
{
//stuff
}
is essentially the same as:
while(true)
{
//stuff
}
It's an empty statement. I never used it, but it exists in many languages.
semicolon(;) indicated the end of a statement. so if you just add a semicolon without anything... it means it is empty statment
An empty statement is sometimes used when a statement expects a block but you don't want it to do anything.
For example:
for(i=0; array[i]!=null; i++)
;
or for nested if then elses without braces:
// don't really do this kids
if(cond1)
if(cond2)
doit();
else
;
else
dont();
Sometimes used for 'if' clarity:
if(somecomplicatedconditionisnotfalseinverted()) // <-- this is already complicated enough, let's not ! that.
; // do nothing
else {
ohnoes();
}
But in your example, it does absolutely nothing when built for release and just adds a nop when built for debug, so you can drop a breakpoint on it.
I'm trying to run a basic loop that will find a specific value in a dataview grid. I cannot figure out whats going on with the code, since the for loop exits before evaluating its basic condition.
private void SearchDataViewGrid(string FileName)
{
//finds the selected entry in the DVG based on the image
for (int i = 0; i == dataPartsList.Rows.Count ; i++)
{
if(FileName == dataPartsList.Rows[i].Cells[3].Value.ToString())
{
dataPartsList.Rows[i].Selected = true;
}
}
}
The program doesn't crash, but i get an error on my 'i' variables declaring that it has been optimised away. Tried a few easy fixes i found online but nothing seems to keep it.
I have verified that the string i am passing is the correct one, and my 'dummy' DVG returns a value of 14 for the number of rows contained. Even if i remove the 'if' statement inside of the for loop, i still get the same error.
The condition cond in the middle of for(init; cond; update) is not an until condition but a while condition.
So you need to change it to
for (int i = 0; i < dataPartsList.Rows.Count ; i++)
The problem is your conditional is i == dataPartsList.Rows.Count so the body will only execute when these two values are equal. This guarantees your loop will never execute. You need to change your conditional to be < instead of ==
for (int i = 0; i < dataPartsList.Rows.Count ; i++) {
...
}
i have an R script that make some calculations.
and i found the same script but in C# , but it's giving me answers different than R.
the R code is :
count=16569
for(ind1 in seq(1,count,by=1000))
{
for(ind2 in seq(1,count,by=1000))
{
value=(count*(ind1^2)) + ((count*(count+1)*((2*count)+1))/6) -(2*ind1*((count*(count+1))/2)) + (2*count*ind1*(count-ind2+1)) + ((count-ind2+1)*(count^2)) + (2*count*(ind2-count-1)*(ind2+count))
}
}
and the C# code is :
double count=16569
for(int ind1=1;ind1<=count;ind1+=1000)
{
for(int ind2=1;ind2<=count;ind2+=1000)
{
value=(count*(Math.Pow(ind1,2))) + ((count*(count+1)*((2*count)+1))/6) -(2*ind1*((count*(count+1))/2)) + (2*count*ind1*(count-ind2+1)) + ((count-ind2+1)*(Math.Pow(count,2))) + (2*count*(ind2-count-1)*(ind2+count))
}
}
for the first round , the value in R is : -3032615095125
but the value in C# is : 4548002182315
what is the error ?
thanks
Looking at your code, I see that the loops won't make any difference. The values from the previous iteration of your loop are never stored or accessed, so value will always be set by the last run of the loop.
In effect, you just have three constants: count = 16569 ind1 = 16001 ind2 = 16001
And the answer is 1.209314e+12, whether or not the loops are run.
In C# (once I add semicolons and a variable declaration for value so it will run):
1209314008875
So I get the same answer in both R and C#. I know you asked why the answers are different, but you might look at whether the code is doing what you want in the first place; I'm not sure why the loops are there. With the code you've given, you could just plug-in the constants above to verify what your machine is giving you.
I don't know R, but with respect to C#, What datatype is the variable value? Could it be that the values are overflowing and therefore junk?
Check the bit sizes of your variables. The value in R looks fishy.
Also, why is count double and not int?
I have written simple math function plotter in C# using Patrick Lundin´s Math free parser.
Now, my code snippet is this:
for (float value = -xaxis; value < xaxis; value += konst)
{
hash.Add("x", value.ToString());
double result = 0;
result = parser.Parse(func, hash);...
This works perfectly for functions defined on real numbers. But, when I want want to parse functions defined only on R+ for example, ln(x), naturally parser gives NaN into result.
Now, I tried to handle it thru exception handling, like so:
for (float value = -xaxis; value < xaxis; value += konst)
{
hash.Add("x", value.ToString());
double result = 0;
try{
result = parser.Parse(func, hash);
}
catch {
count = false; //just a variable I am using to draw lines
continue; // I hoped to skip the "wrong" number parsed until I came to R+ numbers
}...
But this doesen´t work, while debugging, catch is not executed at all.
Please, what am I doing wrong? Thanks.
You say that the parser returns NaN. That is not an exception, which is what a try/catch handles. So there is no exception for the catch block, hence it never being run.
Instead, you should test your result against NaN like so:
if(double.IsNaN(result))...
It sounds as if your parser is just returning NaN, not throwing an exception. You can test for NaN using the static IsNaN method:
result = parser.Parse(func, hash);
if (float.IsNaN(result)) // assuming that result is a float
{
// do something
}
else
{
// do something else
}
You can also try turning on "Check for arithmetic overflow/underflow." It is located in your project properties, under "Build->Advanced Build Settings"
When it is turned on, arithmetic exceptions will be thrown for an overflow and underflow (instead of wrapping). It may or may not apply to the ln function. Give it a try.