converting int var to string var with unassigned local variable error - c#

I am trying to convert an int var to a string var for use in a .txt file. i am coming up with a "unassigned local variable error". I have looked thru other questions but i don't see what i am missing. I have been able to convert int var to a string var before, i am not really sure where i am going wrong. If you could also give me the theory with the solution it would be most helpfull
int sbntmsk;
if (RBSBtn.Checked)
{
sbntmsk = 29;
}
if (BTSBtn.Checked)
{
sbntmsk = 30;
}
string subntmsk;
subntmsk = sbntmsk.ToString();

The compiler has no way to know if your checkboxes will be checked at runtime and so it complains because there is a possibility that the variable sbntmsk reaches the point where you try to convert it to a string without having a value assigned.
To fix the message declare and initialize sbntmsk with (or whatever default value you like)
int sbntmsk = 0;

You need to provide a default value for the integer. For example, what would you expect to be in the string if neither button was checked?

You could just use strings?
var sbntmsk = String.Empty;
if (RBSBtn.Checked)
{
sbntmsk = "29";
}
if (BTSBtn.Checked)
{
sbntmsk = "30";
}

Try using this approach:
int sbntmsk;
if (RBSBtn.Checked)
{
sbntmsk = 29;
}
else if (BTSBtn.Checked) // Notice the ELSE - IF
{
sbntmsk = 30;
}
else
{
sbntmsk = 0; // a default value
}
string subntmsk = String.Empty; // initialize with empty
subntmsk = sbntmsk.ToString();
Since using multiple checkboxes you are assigning to a same variable so no need to check all IF blocks. Also, using this way you have a possibility to define an 'ELSE' block at the end.
Hope it helps!

Related

can I initialization int variable in unity c#?

I want to try initialization int variable
and I think I can use this code.
result = int.Parse("");
Is it work or error?
First of all int.Parse(someString) could produce an exception if the string couldn't be parsed so if you really need to initialize with the value inside a string the better aproach is:
int result = -1; //or any other value that points to an inizialization error
int.TryParse(someString, out result);
or in one line as #Uwe Keim points:
int result;
if (!int.TryParse(someString, out result)) result = -1;
also you can use the horrible try/catch aproach (if for some weird reason you're binded to Parse instead TryParse):
int result;
try
{
result = int.Parse(someString);
}
catch
{
result = -1; //or any other value that points to an inizialization error
}
Or, of course if someString is a constant value you didn't need all the parse problem:
result = 0;

Read only assignment String c#

I'm trying to assign "tela[counter] = letra.ToString();", but it shows up the following error message "Property or indexer 'string.this[int] cannot be assigned to -- it is read only".
I saw some topics saying that you have to define {get;set;} to the atribute, but I've done this, and it didn't work.
[OBS] I tried to create get and set methods but the problem persisted
public String tela { get; set; }
private void btnSendWord_Click(object sender, EventArgs e)
{
char letra = Convert.ToChar(txtGetWord.Text);
MessageBox.Show(comboPalavra[0]);
Boolean codigoVerificador;
codigoVerificador = verificador.VerificaLetra(comboPalavra[0],letra);
if (codigoVerificador == true)
{
foreach(char c in comboPalavra[0].ToCharArray())
{
counter++;
if(c == letra)
{
tela[counter] = letra.ToString();
}
}
}
else MessageBox.Show("Nao contem");
}
Strings are immutable, meaning that you can't change a variable's value without creating a new string.
You are trying to change a single character in a string here, which is not allowed:
tela[counter] = letra.ToString();
A solution to this is to use StringBuilder. You can think of it as a mutable version of string.
You can declare a StringBuilder outside the loop:
var telaBuilder = new StringBuilder(tela);
In the loop, change the erroneous line to:
telaBuilder[counter] = letra;
And after the loop, assign telaBuilder to tela:
tela = telaBuilder.ToString();
Don't forget using System.Text!
This is the signature of the indexer for a string:
public char this[int index] { get; }
See that it returns a char and only has a get, that means it is readonly and you cannot assign something to it. This is why you are getting the error.
If you want to replace a specific letter in a string at a specific position, you can do it like this:
var name = "ferry Seinfeld";
char[] nameArray = name.ToArray();
nameArray[0] = 'J';
name = new string(nameArray);
Please look into Replace method of String and also look into StringBuilder class to see if those will suit your needs.

string multiple string value in one int variable

how to store multiple string value in one int variable
string OutReader = ConfigurationManager.AppSettings["OutReader"].ToString();
int outrdr = Convert.ToInt32(OutReader);
The value of AppSettings["OutReader"] is: "(1,2)"
If AppSettings["OutReader"] currently have in it a string like: "(1,2)"
then you can do:
var sections = ConfigurationManager.AppSettings["OutReader"].Replace("(",string.Empty)
.Replace(")",string.Empty)
.Split(',');
if(sections.Length > 0)
{
int outrdr = Convert.ToInt32(sections[0]);
}
This can still throw an exception in the case that section[0] can't be parsed into an int so use .TryParse instead - Just wanted to stay as close to the question as possible

Not all code paths return a values

I have written a function to find the the line by searching the text and after it find that particular line, I want to read the next line and return that text. The function is as follows:
public static string NextString(string textfind)
{
List<string> found = new List<string>();
string linejd;
using (StreamReader efile = new StreamReader(FILENAME))
{
int counter = 0;
while ((linejd = efile.ReadLine()) != null)
{
counter++;
if (linejd.Contains(textfind))
{
found.Add(linejd);
string nextstring = efile.ReadLine();
return nextstring;
}
}
}
}
File name has been defined as:
const string FILENAME = #"E:\model\Yen and Lee\AQRun01\eratc.inp";
However, I keep on getting error:
AQ.Program.NextString(string)': not all code paths return a value
What if in your function above, your code doesn't enter the loop or the if (linejd.Contains(textfind)) block? The function returns no value!
I tend to recommend declaring a function's result variable and setting its value within the function and then returning it at the end:
static public string nextstring(string textfind)
{
string result = string.Empty;
List<string> found = new List<string>();
string linejd;
/* ********************************************************
* Find the line with certain string */
using (StreamReader efile = new StreamReader(FILENAME))
// using (efile)
{
int counter = 0;
while ((linejd = efile.ReadLine()) != null
&& string.IsNullOrWhiteSpace(result)) // Quit the loop once we have a result!
{
counter++;
if (linejd.Contains(textfind))
{
found.Add(linejd);
string nextstring = efile.ReadLine();
result = nextstring; }
}
}
return result;
}
If the condition linejd.Contains(textfind) is never true then the function will never return anything, yet the function declaration states that it will return a string. You can fix this by returning a default value (such as an empty string) after the using block.
There are two reasons to why the function could exit without a return value:
The file is empty, so the while loop is never entered.
The condition linejd.Contains(textfind) is never true.
Even if you know that the file is never empty, and that the string can always be found in the file, the compiler doesn't know that. (Although, the while loop doesn't make sense if you know that the string can always be found, as that means that you will never reach the end of the file.)
You need to tell the compiler what to do for both those cases, for example by adding return null; at the end of the function.
Alternatively rewrite the code so that it actually relies on the file always containing something and that the string is always found. That way there is no loose ends to take care about. That of course means that the code will crash or hang if the file actually would be empty or the string is not found.
How about using Linq?
public static string NextString(string textfind)
{
return File.ReadLines(FILENAME)
.SkipWhile(line => !line.Contains(textfind))
.Skip(1)
.First();
}
when the if case is always fault, then your method will return nothing.. That's why you get an error.
try writing a return value before the end of your method like:
public static string NextString(string textfind)
{
List<string> found = new List<string>();
string linejd;
string new_string = string.Empty;
using (StreamReader efile = new StreamReader(FILENAME))
{
int counter = 0;
while ((linejd = efile.ReadLine()) != null)
{
counter++;
if (linejd.Contains(textfind))
{
found.Add(linejd);
string nextstring = efile.ReadLine();
return nextstring;
}
}
}
return (new_string);
}

Modifying values within a list

I've been trying to write a program which can scan a raw data file and normalize it for data mining processes, I've trying to read the data from the file and store it in a list this way:
public static List<Normalize> NF()
{
//Regex r = new Regex(#"^\d+$");
List<Normalize> N = new List<Normalize>();
StreamReader ss = new StreamReader(#"C:\Users\User\Desktop\NN.txt");
String Line = null;
while (!ss.EndOfStream) {
Line = ss.ReadLine();
var L = Line.Split(',').ToList();
N.Add(new Normalize { age = Convert.ToInt16(L[0]),
Sex = L[1],
T3 = Convert.ToDouble(L[2]),
TT4 = Convert.ToDouble(L[3]),
TFU = Convert.ToDouble(L[4]),
FTI = Convert.ToDouble(L[5]),
RC = L[6],
R = L[7]
});
}
return N;
}
}
struct Normalize {
public int age;
public String Sex;
public double T3;
public double TT4;
public double TFU;
public double FTI;
public String RC;
public String R;
}
At this moment I want to go through the list that I've made and categorize the data , similar to this :
var X= NF();
for (int i = 0; i < X.Count; i++) {
if (X[i].age > 0 && X[i].age <= 5) { // Change the X[i].age value to 1 }
else if (X[i].age > 5 && X[i].age <= 10) { // Change the X[i].age value to 2 }
...
}
But the compiler says X[i].[variable name] is not a variable and cannot be modified in this way. My question is, what would be an efficient way to perform this operation.
struct Normalize is a value type, not a reference type, therefore you cannot change its fields like that. Change it to class Normalize
Change struct Normalize to class Normalize and iterate with foreach loop. It's way cleaner.
You could also set variables to private and use getters/setters to check/set variable.
foreach (Normalize x in X)
{
if (x.getAge() > 0 && x.getAge() <= 5)
x.setAge(1)
...
}
Edit:
just saw you already got your answer
Modifying struct field is fine as long as it's a single entity (Given its a mutable struct). This is possible -
var obj = new Normalize();
obh.Age = 10;
But in your case you are accessing the struct using indexer from the list.
Indexer will return copy of your struct and modifying the value won't reflect it back to the list which ain't you want.
Hence compiler is throwing error to stop you from writing this out.
As Alex mentioned, you should go for creating class instead of struct if you want to modify it.
On a side note, its always advisable to have immutable structs instead of mutable structs.

Categories

Resources