How to use value assigned within a for loop - c#

I declare the variable setPassword outside of the loop and then give it a value within the loop. Then in the next do-while loop I try to use the value assigned but it says "Use of unassigned local variable".
profile[I] is an array of objects that are created prior to the loops. Is the value being assigned in the loop not saving or is the value of profile[I].Password null because the object hasn't been created yet?
bool good = false;
string username;
do
{
bool broke = false;
Console.WriteLine("Please create a username");
username = Console.ReadLine();
for (int i = 0; i < profile.Count; i++)
{
if (username == profile[i].Username)
{
Console.WriteLine("The username already exists");
broke = true;
break;
}
}
if (broke == false)
{
good = true;
}
} while (good == false);
Console.WriteLine("Please create a password");
string password = Console.ReadLine();
profile.Add(new Users(username, password, 0));
string setPassword;
bool validUser = false;
do
{
Console.Clear();
Console.WriteLine("Enter your username");
string tryUsername = Console.ReadLine();
for (int i = 0; i < profile.Count; i++)
{
if (profile[i].Username == tryUsername)
{
setPassword = profile[i].Password;
validUser = true;
}
}
if (validUser == false)
{
Console.WriteLine("Invalid username. Usernames are case sensitive");
Thread.Sleep(2500);
}
} while (validUser == false);
bool validPass = false;
do
{
Console.WriteLine("Enter your password");
string tryPass = Console.ReadLine();
if (tryPass == setPassword) //this is the error
{
validPass = true;
}
else
{
Console.WriteLine("Invalid password. Passwords are case sensitive");
}
} while (validPass == false);

The compiler can't know it will actually get assigned (and it doesn't if not all if statements you have evaluate to true).
Assign a default value and you will be fine:
string setPassword = null;

I initiate the variable setPassword outside of the loop and then give it a value within the loop.
This is the problem. The system cannot guarantee that a value is assigned before it is used.
It is possible that the loop iterates 0 times.
It is also possible that condition of the surrounding if statement evaluates to false.
Both of these situations lead to setPassword never getting a value.
So the compiler gives you an error, it is possible that you are using setPassword before it has a value.
The solution is to set it to a default value outside the loop, and outside the if.

This is because the compiler can´t know that your for-loop is executed at least once and in particular that the if-statement within the loop also passes at least for one iteration of that loop. Thus - at least from the perspective of the compiler - it is possible that setPassword is never assigned a value and thus you get that error.
Assign null at the start:
string setPassword = null;

Basically the problem is this :
You are using them in mostly the if statements, the if statements uses a variable. But you only declared but never defined the variable globally/locally, which automatically gives an error, despite the variable will be taking a user's input locally, the if statement is unfortunately too stupid to detect that for you, plus it also takes the possibility that the user skips the step of giving an input too. Hence, you need to set a default value.
Like what they stated, you can use :
string setPassword = null; or string setPassword = "";
[Don't need to mind nullables , strings can be null by default]

To solve your problem, you should assign setPassword to string.Empty, null, or some other value, based on your use case
If you are curious about -
Why does the compiler complain that the variable is unassigned even though you assigned a value to it in while loop?
This is called the Definite Assignment behavior of the C# language. A variable is considered to be definitely assigned if
The variable was initialized at the time of declare - either with a default value or an explicitly value
Otherwise, if the compiler can prove, by static flow analysis (in simple words, compile time checks), that all possible execution paths leading up to the first use of variable will assign a value to the variable. Note, the static flow analysis is the key here, the compiler does not evaluate or take for granted that any run-time possibilities (conditions in if, while, for etc. control statements) will eventually assign the variable a value.
See Definite assignment at MSDN for more info. It is an archived document but should still be good a reference.
Also DotNetPerls Page describes it in simple language.
Disclaimer: I have no association with DotNetPerls.

Related

C# How to make use of return true/false from a method (outside of loop) called from within a while loop

I am trying to write a program that lets me enter a list of names with their respective film rating into an array (Would do a list but the course material wants me to use array). Before I add the names to the array I want to make sure that a valid rating has been entered.
I am currently using a for statement that cycles through he array length and lets the user enter each movie to the list that way. This happens in a while loop to make them re-enter the name if the rating is invalid before the name is committed to Array. I check the names by calling a method with a temporary string assigned with the current entered name and rating which will do some conditional checks and return either false or true depending on the outcome. But the way I am doing it is not working at all..
Problem is that I have no idea how to make practical use of the bool statement my method returns:
string[] filmNames = new string[ArrayLength];
for (int i = 0; i < filmNames.Length; i = i + 1)
{
bool ratingFail = true;
int displayNumber = i + 1;
while (ratingFail)
{
Console.Write($"> Enter the Name and Rating of film number {displayNumber} of {ArrayLength}: ");
string checkRating = Console.ReadLine();
CheckRating(checkRating); // currently just does "return false;" for testing purposes
if (true) // this statement is clearly not effected by whatever the return value is from above method. Why? What to do?
{
ratingFail = true;
}
else
{
filmNames[i] = checkRating; // this bit is marked as unreachable, which is is.
ratingFail = false;
}
}
}
my test method:
public static bool CheckRating(string checkRating)
{
return false;
}
I am VERY (a week) new to programming and C# so please keep in mind when answering that I may not understand particular lingo referring to programming terms outside of the scope of what you can see here within, but I will Google and research to the best of my abilities if there is no way to simplify what you want to say. Thank you for your time and effort.
if (true) // this statement is clearly not effected by whatever the return value is from above method. Why? What to do?
{
ratingFail = true;
}
This will always be true, because you're creating a variable that is always true. You want this:
ratingFail = CheckRating(checkRating)
if (!ratingFail) {
The rating is valid, do stuff here.
}
If ratingFail is true, the loop will continue.
This assumes that CheckRating returns true if the input is invalid, and false if it is valid. The variable naming here is pretty confusing, and I recommend you refactor.
I would do it this way, assuming CheckRating returns true if valid:
for (int i = 0; i < filmNames.Length; i = i + 1)
{
bool ratingValid; // Defaults to false
int displayNumber = i + 1;
while (!ratingValid)
{
Console.Write($"> Blablabla: ");
string input = Console.ReadLine();
ratingValid = CheckRating(input);
}
// Do stuff if rating is valid here. If you got here, rating is valid.
}
// edit by iluvpancakes //
I decided to add a comment made by #Sinatr since that was the (version of the) solution I personally ended up using:
if(CheckRating(checkRating))
{
[do stuff and things]
}
bool ret = CheckRating(checkRating); // currently just does "return false;" for testing purposes
if (ret)
{
[...]
}
Or, like Sinatr's comment:
if(CheckRating(checkRating))
{
[...]
}

error: cs0131 The left-hand side of an assingnment must be a variable, property or indexer

I've tried to make a text adventure and a got an error when I get to the "if" part. I got it to work once but not like I wanted it.
I changed it a bit and then gave up and went to the original script but it wasn't working like last time and instead gave me this error:
cs0131 The left-hand side of an assingnment must be a variable,
property or indexer
Here is my code:
Console.WriteLine("What's your name");
string name = Console.ReadLine();
Console.Write("Hello " + name);
Console.WriteLine(" do you like games?");
Console.WriteLine("yes or no");
string yes = Console.ReadLine();
string no = Console.ReadLine();
if (Console.ReadKey() = yes) { Console.WriteLine("Great!, Lets play one"); }
//the error is at "if (console.readkey()"
In C# and many languages, there is a distinction between assigning a variable is equal to a value and testing for equality.
In C# = is used to assign values. int x = 1; will create a variable with the value 1.
== is used to test a value, so you would write if (x == 100) { /* something */ }
Going on your current code, you probably should have something more like this:
Console.WriteLine("yes or no");
string answer = Console.ReadLine();
if (answer == "yes") { Console.WriteLine("Great!, Lets play one"); }
Major differences are:
You are reading the answer a user types after asking yes or no, however in your code you are then trying to re-read another answer. Which doesn't quite make sense. The console will hang until the user enters another response.
As JamesFaix said, you are then trying to assign a value to Console.ReadKey() of whatever the user responded with first, after you asked them if they want to play. Instead you should be checking if the user's response was a positive reply.

Unassigned variable in return statement

for some reason I don't seem to be able to put the return in a fashion that captures this stored procedure's return value (0 or -1), either it returns the value which was used to initialize the variable or keeps telling me the local variable is unassigned.
public int changePass(int idUsuario, String old_pass, String new_pass)
{
int result;
try
{
DataTable tablaResultado =
DataBaseAccess.advanceStoredProcedureRequest(
"pa_usuario_change_pass",
new SPP[]
{
new SPP("id_usuario", idUsuario.ToString()),
new SPP("old_pass", old_pass.ToString()),
new SPP("new_pass", new_pass.ToString())
});
if (tablaResultado.Rows.Count > 0)
{
if (tablaResultado.Rows[0] != null)
{
result = (int.Parse(tablaResultado.Rows[0].ItemArray[0].ToString()));
}
}
return result;
}
catch (System.Data.SqlClient.SqlException sqlException)
{
throw sqlException;
}
}
I have multiple methods which follow the same pattern and all of those works, I have been trying to get this to work for awhile now, and I'm sure I'm overlooking something very, very obvious. Either way I cannot find it right now so I was hoping someone could refresh my memory or give me a tip.
The code only assigns a value to the result variable if two different conditions both happen to be true. That is, if the row count is > 0 and the first row is non-null. The compiler is telling you, completely legitimately, that your code contains a path to the return statement where the variable being used hasn't been assigned a value yet.
You need to decide what the method should return if either of those conditions are not true, and then assign that value to the result variable as part of its initialization.
EDIT:
To be clear: it seems you may be overlooking the possibility that your code won't successfully execute the stored procedure. But it can only return a value to be assigned to result when those two conditions are true. You either need to pick a default value that is reasonable to return when one or the other of the conditions aren't true, or you need to fix the code so that those conditions are always both true (and so the SP always executes successfully).

Use of unassigned local variable being a pain

I'm trying to make a program that finds the factors of a number. I made a fairly simple one but it always repeated the same two factors twice i.e. 1 and 2, 2 and 1. So, to fix that I tried to check if the number had been used before but it keeps saying the bool proceed is unassigned.
using System;
namespace FactorableOrNah
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("Enter a whole number to view its factors: ");
int userInput = int.Parse(Console.ReadLine ());
int[] antiDoubler = new int[userInput];
bool proceed;
Console.Clear();
for (int i = 1; i != userInput; i++) {
antiDoubler[i] = userInput / i;
for(int j = 0; j < userInput; j++) {
if (antiDoubler [j] == i)
proceed = false;
else
proceed = true;
}
if ((userInput % i) == 0 && i != 1 && proceed == true)
Console.WriteLine("{0} and {1}", i, (userInput / i));
}
}
}
}
Using uninitialized variables in C# is not allowed. The compilation error can be solved by using either:
bool proceed = false;
or
bool proceed = default(bool);
since the default value of bool is false;
However, the algorithm is too complicated and very hard to read. Just for fun. A recursive example.
static IEnumerable<int> GetFactors(int number)
{
return GetFactors(number, number);
}
static IEnumerable<int> GetFactors(int number, int check)
{
if (check > 0)
{
if (number % check == 0)
{
yield return check;
}
foreach (var f in GetFactors(number, --check))
{
yield return f;
}
}
}
UPDATE:
Local variables cannot be left uninitialized, however class members (static members and instance variables), furthermore array elements are initialized automatically by the memory manager, so they are never uniitialized.
From the specification:
A variable must be definitely assigned (§5.3) before its value can be
obtained. As described in the following sections, variables are either
initially assigned or initially unassigned. An initially assigned
variable has a well-defined initial value and is always considered
definitely assigned. An initially unassigned variable has no initial
value. For an initially unassigned variable to be considered
definitely assigned at a certain location, an assignment to the
variable must occur in every possible execution path leading to that
location.
For your case you have an initially unassigned variable. Thus, the variable must be set in every possible execution path. There is one possible execution path to which your variable is not defined - when userInput >= j.
This would happen if userInput is 0. Following your program manually:
The first for case will check if i != userInput. Since i = 1 this is true, thus it will continue in the for loop.
the second for case will check if j < userInput. Since j = 0 this is false, thus it will skip the for case and never set proceed
Now you have arrived to where you check proceed and it was never set. So the compiler tells you that this is not allowed.
To solve your issue, you have to decide whether to:
define a default value for proceed, for instance false and set it at declaration, i.e. bool proceed = false;.
Rewrite your logic so that you do not need the boolean, for instance like Daniel Leiszen suggests.

Local variable and Try/Catch

I get an error, a red line below the variable intAge in the if-statement in the code. It says the variable is local, but how could it be local when it is declared in the beginning of the code? Does it have to do with the Try/Catch part? The reason why my code looks like it does, is just beacuse I have to use a Try/Catch in the code for this task. Preciate some suggestions to solve this in a similiar and correct way? Thanks!
int intAge;
try
{
intAge = int.Parse(age);
}
catch (Exception)
{
MessageBox.Show("Enter an age in numbers!","Error!");
}
finally
{
}
// Check input
if (intAge < 1)
{
inputOk = false;
errorMessage = "Please enter 1 or higher!";
}
just initialize the intAge:
int intAge = 0;
You are getting error use of unassigned local variable.
Since you are assigning the value in the try block, the compiler can't determine if the assignment will take place or not (in case if int.Parse(age) throws an exception), and then in your check if(intAge<1) you are getting the error because you are using a variable not previously assigned.
Definite assignment - MSDN
At a given location in the executable code of a function member, a
variable is said to be definitely assigned if the compiler can prove,
by static flow analysis, that the variable has been automatically
initialized or has been the target of at least one assignment.
If int.Parse fails, the intAge variable will not be initialized.
You may initialize it at delecration
int intAge = 0;
You may avoid the double error :
int intAge;
if (!int.TryParse(age, out intAge))
{
inputOk = false;
errorMessage = "Enter an age in numbers!";
}
else
{
// Check input
if (intAge < 1)
{
inputOk = false;
errorMessage = "Please enter 1 or higher!";
}
}
It's local because it's declared in the local scope. Your code may be better structured like:
int intAge;
if (!int.TryParse(age, out intAge))
{
MessageBox.Show(...
}
else
{
if (intAge < 1)
{
inputOk = false;
errorMessage = "Please enter 1 or higher!";
}
}
With your code above you will display two errors, one for non-numeric, and then one for less than 1. The initial complaint of the compiler was because your integer was not guaranteed to be initialised.
The compiler complains that the local variable intAge might not have been initialized when used for the first time. This may happen when int.Parse(age) throws an exception. To correct this, just initialize intAge to some proper value.
The problem is age is not initialized initialize it to 0 , and try . it must work

Categories

Resources