can I initialization int variable in unity c#? - 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;

Related

Not all code paths return a value c#

I have declared a method in a class to compare two numbers and I'm having an issue. I'm getting an error saying not all code paths return a value. I want to return an int for every matching number in the char arrays.
Here is an image of the code.
public int CompareCodes(string rndselect, string personselect)
{
char[] rndnumber = rndselect.ToCharArray(); //take the randoms elected one and convert it to a char array
char[] perNum = personselect.ToCharArray();
likeness0 = 0;
likeness1 = 1;
foreach (char RndNum in rndnumber)
{
foreach (char Pnum in perNum)
{
if (RndNum == Pnum)
{
return likeness1;
}
else
{
return likeness0;
}
}
}
}
What should compiler think if your perNum is empty?
The error says exactly what is wrong with your code. Having a foreach loop doesn't guarantee anything inside the foreach is executed. If rndnumber or perNum happens to be empty, there is nothing to loop through and your code actually doesn't return anything.
If rndselect or perNum is empty string.
So no value is returned.
If you sure these string are always not null. so add
return 0
at the end of block.

Having trouble converting string to int

In my program I have a treeView. In the section that I am working with, the node's displayNames are numerical integer values, but are displayed as strings. I have come to a point in my program where I need to convert and temporarily store these displayNames in an integer variable. I usually use Regex.Match() to do this with no problem, but in this scenario I am getting the compiler error: Cannot implicitly convert type 'string' to 'int'.
This is my code:
//This is the parent node as you may be able to see below
//The children of this node have DisplayNames that are integers
var node = Data.GetAllChildren(x => x.Children).Distinct().ToList().First(x => x.identify == 'B');
//Get # of children -- if children exist
if (node.Children.Count() > 0)
{
for (int i = 0; i < node.Children.Count(); i++)
{
//Error on this line!!**
IntValue = Regex.Match(node.Children.ElementAt(i).DisplayName.Value, #"\d+").Value;
}
}
*NOTE: DisplayName.Value is a string
To get from string to int, use int.Parse(string), it returns the int represented by the passed string and throws if the input format is incorrect.
int.Parse(node.Children.ElementAt(i).DisplayName.Value)
You can also use int.TryParse if you don't want the throw. in that case you would use:
int parsedValue;
if (int.TryParse(node.Children.ElementAt(i).DisplayName.Value, out parsedValue))
{
///Do whatever with the int
}
The problem is becuase you're casting from Match to int in this call
IntValue = Regex.Match(node.Children.ElementAt(i).DisplayName.Value, #"\d+").Value;
Try something like this:
Match m = Regex.Match(node.Children.ElementAt(i).DisplayName.Value, #"\d+").Value;
int value = m.Matches[0] //You'll have to verify this line, I'm going from memory here.

Input string was not in a correct format. Converting string to int

Input string was not in correct form.
I'm getting an exception on runtime as "System.FormatException".
Follwing lines shows exception-
public int Task
{
get
{
return Int32.Parse(TaskText.Text);
}
set
{
TaskText.Text = value.ToString();
}
}
public int Project
{
get
{
return Int32.Parse(ProjectText.Text);
}
set
{
ProjectText.Text = value.ToString();
}
}
I also tried -
Convert.ToInt32(TaskText.Text)
Convert.ToInt32(ProjectText.Text)
I need to pass these to following constructor,
Harvest_TimeSheetEntry entry = new Harvest_TimeSheetEntry(client,starttime,stoptime,task,project);
this constructor is stored in some class with task and project as integer parameters. And I can't change it because if i changed, it affects other code.
It looks as though you're getting your input from controls accepting user input, which is just asking for failure, since a user can potentially enter something that doesn't represent an integer value. You can use TryParse to avoid this:
var result = 0;
if (int.TryParse(TaskText.Text, out result)) {
return result;
}
return 0;
So, if the value of TaskText.Text == "1", this will succeed; if the value of TaskText.Text == "aaaa", this will fail - and return zero. You example would raise the appropriate exception, as experienced.
However, an exception might be the right thing to happen here, if you can't handle a bad value, don't have an alternative, and the application relies on the input to move forward. More likely, you could do with some validation on your input fields to prevent bad data being submitted.
Since your Harvest_TimeSheetEntry constructor expects task and project to be integers, you must have a list of integers that correspond to the different tasks and projects. Now you can't expect Int32 to know which task corresponds to which number, can you?
I would suggest you use ComboBoxes for TaskText and ProjectText. Then, you can assign the correct corresponding integer to each ComboBoxItem.Tag.
Please note that this goes far beyond the kind of answers you should expect from SO.
if you do not use MVVM or binding you can simply do the check before your need it. t
int task;
int project;
if(!Int32.TryParse(TaskText.Text, out task))
{} //errorhandling here
if(!Int32.TryParse(ProjectText.Text, out project))
{}//errorhandling here
//all fine
var entry = new Harvest_TimeSheetEntry(client,starttime,stoptime,task,project);
You must check if you can parse it into Integer
try
Int32 foo =0;
if (Int32.TryParse(TaskText.Text, out foo))
{
return foo;
}

converting int var to string var with unassigned local variable error

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!

Better syntax for a return statement in a method which retrieves a query String

I use this simple method to retrieve a Query String from a Page a returning a Int. In case a valid Id can not be found I would like return a default value int 0.
I would like to know if there is a better way to write this method, in details:
Would be better use just a single return statement instead the two? If yes what is the best way to do it?
Shall I perform any other checking when retrieving the Query String?
protected int GetPageIndex()
{
int output;
bool result = Int32.TryParse(Request.QueryString["page"], out output);
if(result)
return output;
return output = 0; // Return Default value
}
Just initialize it before you try to parse it... Anyways, Int32.TryParse sets the value to 0 if the conversion is unsuccessful... :) http://msdn.microsoft.com/en-us/library/f02979c7.aspx
protected int GetPageIndex()
{
int output = 0;
Int32.TryParse(Request.QueryString["page"], out output);
return output;
}
You're safe to simply return output, since you're seemingly not concerned as to whether TryParse succeeded or not, and by assigning a value of 0 to output initially, for clarity, then that is what will be returned if TryParse fails anyway.
protected int GetPageIndex()
{
int output = 0;
int.TryParse(Request.QueryString["page"], out output);
return output;
}
How about this to use less code, with regards to checking the query string I dont think you need to check for null as the try parse should handle the null value.
protected int GetPageIndex()
{
int output;
return Int32.TryParse( Request.QueryString[ "page" ], out output ) ? output : 0;
}
int output;
return Int32.TryParse(Request.QueryString["page"], out output) ? output : 0;
I'd go with
protected int GetPageIndex()
{
int output = 0;
Int32.TryParse(Request.QueryString["page"], out output);
return output;
}

Categories

Resources