c# How to put value outside of for looping? - c#

I am starting to learn C#. I want to know how to put a value outside of a for loop like this:
int firstByte;
if (bytes == 1)
{
for (int j = 0; j < bytes; j++)
{
firstByte = comBuffer[j];
if (firstByte == 0x06)
{
checkStatus = 2;
}
}
}
bytes is the length of comBuffer, and comBuffer's value is [0x01,0x06]. Is that a way to put the if(firstbyte == 0x06) outside of the for loop?. I want to put it outside of the for loop because I want add another if-else using if(firstbyte) outside of the loop.
My expectation is some like this:
int firstByte;
if (bytes == 1)
{
for (int j = 0; j < bytes; j++)
{
firstByte = comBuffer[j];
if (firstByte == 0x06)
{
checkStatus = 2;
}
}
}
if(firstByte == 0x06)
{
string status = "OK";
}
When i try it, the program shows a warning message "unasigned value .....".
Any solution or suggestion?

Let's first understand what the problem is.
int firstByte;
**if (bytes == 1)**
{
for (int j = 0; j < bytes; j++)
{
firstByte = comBuffer[j];
if (firstByte == 0x06)
{
checkStatus = 2;
}
}
}
if(firstByte == 0x06)
{
string status = "OK";
}
firstByte is assigned a value only if bytes is 1, so there is this possibility of firstByte not being assigned anything and being checked in the outside if condition. You can easily avoid this problem by assigning firstByte a value like 0 or something that doesnt interfere with your logic.
int firtByte = 0;
will solve your problems.

assign default value at the time of declaration
int firstByte = 0;

int firstByte;
Your firstByte must have some value when assigning it.
for example:
int firstByte = 1;
Oherwise it cant be used with if because it has not the value to compare in statement.

When you declare a variable in your code without initializing it with a value, the compiler will throw an error if you try to access that variable unless your code guarantees that it will be assigned a value before it is accessed. In your example, you declare int firstByte; without assigning it a value. It doesn't receive a value until firstByte = comBuffer[j];, which is inside an if-block and a for-loop, either of which could conceivably skip the execution of their bodies without reaching that line of code.
Initializing firstByte with a value (such as int firstValue = -1;) will solve your issue.

Yes it is possible in two ways,
Make int firstByte as global
Assign a default value for firstByte.
Something like the following:
int firstByte=0;
Or
int firstByte=0X64;
Or some other values as per your requirements.
Why compiler is showing such message : Their may be chances for the condition bytes==1 evaluates to false, or the looping skip the loop. in such cases there is no assigned value for firstByte when you try to check it outside those conditions. Hence it shows the warning to make it perfect

I usually use nullables in this case:
int? firstByte = null;

Related

Scope of variables error

I'm pretty much new to C# programming.
I found this weird scope error in my program, my program won't run. It said below (at lbl[tx].BackColor = Color.DarkViolet;) that "Used of unassigned local variable". But I already declared variable tx inside in my method.
How to fix this? Any help is pretty much appreciated.
async void ShellSort()
{
int n = num.Length;
int gap = n / 2;
int temp;
int tx; /// Already declared tx here
while (gap > 0)
{
for (int i = 0; i + gap < n; i++)
{
int j = i + gap;
temp = int.Parse(lbl[j].Text);
while (j - gap >= 0 && temp < int.Parse(lbl[j - gap].Text))
{
lbl[j-gap].BackColor = Color.Blue;
lbl[j].BackColor = Color.Blue;
await Task.Delay(time1);
lbl[j].Text = lbl[j - gap].Text;
tx = j;
j = j - gap;
}
lbl[j].Text = temp.ToString();
lbl[j].BackColor = Color.DarkViolet;
lbl[tx].BackColor = Color.DarkViolet; /// When I used
/// it here it wont work.
}
gap = gap / 2;
}
}
You declare the variable, but don't assign anything to it:
int tx;
You might assign to it in your loop:
while (j - gap >= 0 && temp < int.Parse(lbl[j - gap].Text))
{
//...
tx = j;
//...
}
// use tx here
But, what happens if that loop condition starts out as false? If the loop is never entered, no value is ever assigned. The compiler can't risk that. Though you might assign it a value, the compiler needs to ensure that you do assign it a value.
You can do this by simply assigning it a default value:
int tx = 0;
Integers default to 0 anyway when it comes to properties and whatnot. So one may as well do the same with local variables.
If body of your while will be never executed, tx will be unassigned. Compiler just tells you that you need initial value for this case.
So instead of
int tx;
write
int tx = 0; // or what is the correct value for you

Use of unassigned local variable please [duplicate]

This question already has answers here:
What does "Use of unassigned local variable" mean? [duplicate]
(11 answers)
Closed 6 years ago.
I created much for loops and want to put
value from a int to a string.
String strasze = dataGridView1.Rows[rows].Cells[straszeint].Value.ToString();
String stadt = dataGridView1.Rows[rows].Cells[stadtint].Value.ToString();
land = dataGridView1.Rows[rows].Cells[landint].Value.ToString();
hersteller = dataGridView1.Rows[rows].Cells[colIndex].Value.ToString();
kundennummer = dataGridView1.Rows[rows].Cells[kundennummerint].Value.ToString();
haendler = dataGridView1.Rows[rows].Cells[haendlerint].Value.ToString();
Here is a example for loop:
int landint;
for (int i = 0; i < datagridview.Columns.Count; i++)
{
if (datagridview.Columns[i].Name.Equals(landname))
{
landint = i;
break;
}
}
What is wrong? It shows me the error on
straszeint,
stadtint,
landint
//EDIT
int straszeint;
for (int i = 0; i < datagridview.Columns.Count; i++)
{
if (datagridview.Columns[i].Name.Equals(straszennamen))
{
straszeint = i;
break;
}
}
From your code, it is possible straszeint is never assigned a value. Assume what happens if datagridview.Columns.Count is 0, or there is no column matching the name. Then straszeint is never set to a value.
The compiler doesn't know what you know, so it just checks all paths and sees if there is a possible problem with an unset variable.
The easiest thing to do here is to set the variable to some arbitrary number and check that later:
int straszeint = -1;
for (int i = 0; i < datagridview.Columns.Count; i++)
...
if (straszeint == -1)
{
throw new Exception("Column 'straszennamen' could not be found!");
}
This is because Compiler is smarter than a developer
You should Initialize the local variables before accessing their values, In your case there may be changes for skipping the iteration of the loop, or the condition inside the loop will evaluate to false in all iteration. and you are using the value (say straszeint) after the iterations.
Compiler expecting such situations that's why it showing such errors.
You can simply solve this by initializing the variable either with 0 or any other value that's up to you.
int straszeint=-1;
for (int i = 0; i < datagridview.Columns.Count; i++)
{
if (datagridview.Columns[i].Name.Equals(straszennamen))
{
// Let it is false for all iterations
straszeint = i;
break;
}
}
// straszeint will be -1 here if the condition is false for all iteration
if(straszeint!=-1)
{
//Proceed with the action
}
Updates : Why should we initialize with -1 instead for 0
The .Cells will follows the 0 based indexing, So it will give the First cell value even if the condition evaluates to false.

c# foreach looping even number

I have the following foreach loop in C#:
foreach(var item in mod)
{
int i;
i = i + 1;
if (i % 2 == 0)
{
string y = "even number";
}
}
How come I get the message that local variable is unassigned. I am trying to find the even number here.
To resolve the message you are getting, you simply need to initialize it:
int i = 0;
If your intention is to count every item, then you will also need to change the scope of i to outside of the foreach. Otherwise, as you originally posted, the variable i will have the same value for every iteration of the loop.
See this code snippet for both the initialization and scope change:
int i = 0;
foreach (var item in mod)
{
i = i + 1; // is the first item considered even or odd? that answer changes where this should go
if (i % 2 == 0) {
string y = "even number";
}
}
You need to initialise your i variable:
int i = 0;
You're currently trying + 1 to an unassigned variable.
You get the warning because you are not assigning i before using it in i = i + 1. You want to declare i outside of your foreach loop, so you it isn't bound to the scope of the loop. Then initialize with 0 and use the increment feature. Something like:
int i = 0;
foreach (var item in mod)
{
i++;
if (i % 2 == 0)
{
string y = "even number";
}
}
An alternative to what others have suggested here (although correct) would be to use a for loop, this would take care of i for you, e.g.
for (int i = 0; i < mod.length; i++)
{
if (i % 2 == 0)
{
string y = "even number";
}
}
Change this: int i;
to this: int i = 0;
Values types in C# like int do have default values, but you're still not allowed to use an unassigned value-type variable.
You need to assign an initial value for i before you can do i=i+1
You have to initialize i. Right now the compiler is reading this as i = garbage in memory. So you have garbage in memory = garbage in memory + 1. That i could be equal to a string, a number, or anything.
int i = 0;
In addition, you need to initialize that variable outside of the for...each loop, or it will keep resetting itself to 0.
int i = 0;
foreach(var item in mod){
i = i + 1;
if (i % 2 == 0) {
string y = "even number";
}
}
int i = 0;
foreach(var item in mod)
{
if (i % 2 == 0)
{
string y = "even number";
}
i = i + 1;
}
//what are you doing with y and how are you returning y if you need it..
are you expecting to break out at some point.. ? what if item has zero items..??

Cannot implicity convert int to bool

Okay, so I'm getting a "cannot convert int to bool" error.
I'm trying to convert this VB .net code:
Function GetChecksum(ByVal Source As String) As Long
Dim iVal, Weight, CheckHold, CheckSum As Long
Weight = 1
CheckSum = 0
For iVal = 1 To Len(Source)
CheckHold = Asc(Mid$(Source, iVal, 1)) * Weight
CheckSum = CheckSum + CheckHold
Weight = Weight + 2
Next iVal
GetChecksum = CheckSum Mod &H7FFFFFFF
End Function
I've gotten up to here:
public long getCheckSum(string source)
{
long iVal, weight, checkgold, checksum = new long();
weight = 1;
checksum = 0;
for (iVal = 1; Strings.Len(source);)
{
}
}
The problem is the "For (iVal = 1; Strings.Len(source);)" code. I am using "Microsoft.VisualBasic". I just don't know what to do right now. If you could help me that'd be great.
Looks like you need to set your loop correctly. In C#, a for loop (generally) follows the following format:
for(initializer; conditional check; evaluation)
initializer is where you set variables like iVal = 1
conditional check is where you determine the bounds of the for loop
evaluation is usually where you increment a variable
In your code, you have an integer, Strings.Len(source), as the conditional check, which is expecting a boolean response so it's failing.
Your for loop opener should look something like this:
for (iVal = 1; iVal < source.Length; iVal++)
That's assuming your logic is 0 < iVal < length of source string.
As an aside, the way you check the length of a string in C# is with the .Length property, rather than using the Strings.Len() function.
for (iVal = 1; iVal < source.Length; iVal++)
{
}
The middle section is a condition.
You will need:
for (iVal = 1; iVal <= source.Length; ival += 1)
But be aware this loops through 1..source.Length,
not the more common (in C#) 0..source.Length-1
As the others have already solved your problem, I only want to add for future reference that you might want to check out Convert VB to C#.
I've used it myself on a number of occasions with pretty good results.
Standard syntax of for loop:
for(counter initialize; counter compare; counter increment) {}
The comparison expects a bool, you're providing an int with Strings.Len(source), which returns some number, not a Boolean value like true or false.
Try
for(iVal = 1; iVal < String.Len(source); iVal++)
You may want to use <= since your starting at 1 or set iVal to 0
Your For syntax should looks something like this :
For(ival = 1; source.Length; ival++)
{
// your code here
}
ival++ will replace the "Next" in VB.
Rather than translate the for loop literally into C#, I'd use a foreach, as you're doing a straightforward iteration over the elements of a sequence (each char in the string):
public long getCheckSum(string source)
{
long checkHold = 0, checkSum = 0, weight = 1;
foreach (char ch in source)
{
checkHold = (long)ch * weight;
checkSum += checkHold;
weight += 2;
}
return checkSum % 0x7FFFFFFF;
}
you want
for (iVal = 1; iVal <= source.Length; iVal++)
{
//your code here
}
Alternatively, if you want to leave iVal alone (because you need it "pure" for something later)
for(i = iVal; i <= source.Length; i++)
{
//your code here.
}

C# - Error "not all code paths return a value" with an array as out parameter

I currently have the below code:
public int GetSeatInfoString(DisplayOptions choice, out string[] strSeatInfoStrings)
{
strSeatInfoStrings = null;
int count = GetNumOfSeats(choice);
if ((count <= 0))
return 0;
strSeatInfoStrings = new string[count];
int i = 0;
for (int index = 0; index <= m_totNumOfSeats - 1; index++)
{
if (string.IsNullOrEmpty(m_nameList[index]))
strSeatInfoStrings[i++] =
m_nameList[index].ToString();
}
}
This code produces an error of, "...GetSeatInfoString.DisplayOptions, out string[])': not all code paths return a value. Basically, what I am looking to do in the above method is to cycle through an array and for any values in the array that contain a string, I want these then adding to the new array, strSeatInfoStrings which in turn, can be called from a separate class and the new array content then displayed in a listbox.
Any suggestions on how to rectify this?
Thanks in advance
You have no final return before the method exits. You are exiting if there are no elements but you need a return at the end. If you are not interested in the value then why not set the return type to void?
You can add return strSeatInfoStrings.Length at the end
public int GetSeatInfoString(DisplayOptions choice, out string[] strSeatInfoStrings)
{
strSeatInfoStrings = null;
int count = GetNumOfSeats(choice);
if ((count <= 0))
return 0;
strSeatInfoStrings = new string[count];
int i = 0;
for (int index = 0; index <= m_totNumOfSeats - 1; index++)
{
if (string.IsNullOrEmpty(m_nameList[index]))
strSeatInfoStrings[i++] =
m_nameList[index].ToString(); }
return strSeatInfoStrings.Length;
}
You need to return an integer value according to your methods signature.
After the for loop is where a value should be returned.
The error isn't anything to do with your out parameter.
Your method
public int GetSeatInfoString(
DisplayOptions choice, out string[] strSeatInfoStrings)
is declared as returning an int, and doesn't do this for all code paths.
You are only returning a value if count <= 0. Either you need to return a value after the for loop, or change the method signature to be void, depending on what you want the return value to represent.
If you want to return the array with the counts in, then change the return type to string[] and remove the out argument.
What value do you want to return from this function? I guess that you need to add this line to the end:
return i;

Categories