Storing the result of a test in a variable - c#

I am new to C# (and programming in general) so I am unsure how to ask this using proper terms (please bear with me):
What I am trying to do is, if a set of conditions are true, I want to create a new value that is true (so it equals 1). A new set of conditions later in the code will contain the new value as a variable (along with a number of other new conditions). Basically it will look like this:
// Condition set 1
if (Position.GetProfitLoss(Close[0], PerformanceUnit.Percent) < -0.015)
{
//this section will have a newly created value ('variable1')
//that if true will equal 1, and if false will equal 0
}
in the next condition set, the previously created variable will be a part of the decision:
// Condition set 2
if (RVI>50)
&& variable1=1
{
Buy100Shares
}
How do I define the first variable?

You define the first variable as a boolean. C# offers you the bool type:
bool meetsThreshold = (Position.GetProfitLoss(Close[0], PerformanceUnit.Percent) < -0.015);
After this line of code has executed, meetsThreshold will either be true or false.
You can then use this variable in later predicates:
if ((RVI>50) && meetsThreshold)
{
Buy100Shares
}

Related

How to use value assigned within a for loop

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.

What does variable = !variable mean?

I have this code. What does it mean?
bool q = false;
if (i < 0) {
q = !q;
}
I assume !q means true?
UPDATE: The full code is below. When ! is used in the IF statement, is the variable in that situation always false?
bool q = false;
if (i < 0) {
q = !q;
}
if (!q) {
/// do stuff
}
All it means is it's "not q", so it's opposite of whatever q is.
In the case of a boolean like here, the variable q can be either true or false.
when you put a ! in front of something in most languages, it means "opposite"
As example,
1 != 2
means:
1 is opposite of equal to 2
.
This being for a condition, in your case, it would mean
assign the opposite of q to q.
Also, I believe most people on SO (Stack Overflow) will tell you this question does not belong here because you can find it easily on the internet, if you want, there are various books to learn programming. You can search "it ebooks" on the internet and you will probably find many for free .
As the other poster said, it switches the bool property from true to false. In your example, q starts as false. If i is less than 0 then q becomes true. Then comes the if statement, which says "if q is false, then execute the next code block". q only stays false if i is greater than or equal to 0. So no, the code inside your if block will not always execute. It depends on i.

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).

Can you Make a Boolean value turn off/on automatically?

Okay I have declared a Key CellX to boolean value True. In a sense as long as this value remains true my data will keep inserting in and If I turn it false it will stop at what ever count it was on. Now I have to Stop at when 400 orders have been inserted in data base and no more... can I actually apply a condition
like
Key CellX "True"
if CellX ==400 then "False"
else
"True"
can we accomplish this... I am doing in C#.
I C most of you have given good logic.
little more CellX is declared in web.xml along with other keys such as CellA, B, C and A, B, are receiving data in DB so to stop it from reaching 400 I can manually change the CellX Boolean Value or How can I implement a condition which will make my Boolean value to turn false when Cell A, B, C reach 400.
You can do something like
myBool = (CellX == 400);
However, in your post you refer to CellX as both a boolean and as something that can be compared to an integer value of 400. A given variable can be boolean or an integer.
If CellX is your boolean, instead do something like:
CellX = (myLoopCounter == 400);
The syntax
myBool = (myLoopCounter == 400);
evaluates like this:
Evaluate whether myLoopCounter is exactly 400 (true, or false)
Assign the result of the previous step to myBool
A variable can't be dynamically evaluated like that (at least not in the way I think you're looking for, things like Func notwithstanding). But you can create it as a read-only property on the class which would be evaluated each time (since a property is mainly a syntactically different form of a method call):
private bool LimitReached
{
get
{
return (CellX == 400);
}
}
So if you keep checking the value of LimitReached over and over, it should potentially change if the value of CellX is also changing.
Is this what you're trying to do?
int Counter = 1;
bool Continue = true;
while(Continue)
{
// Insert one row
if (Counter == 400)
Continue = false;
Counter++;
}
This can also be written:
for(int i = 0; i < 400; i++)
{
// insert one row
}

Returning booleans in a C# method

I have an array of booleans which gets filled by a loop. The method that owns the array needs to return a single boolean. So can I do this:
bool[] Booleans = new bool[4];
// do work - fill array
return (Booleans[0] && Booleans[1] && Booleans[2] && Booleans[3]);
So if I have: T,T,F,T will I get F back since there is one in the array or will it send back something else or just crash all together?
A single false will result in false being returned with boolean AND logic.
You can also rewrite as:
return Booleans.All(b => b);
For the sake of completeness, or if LINQ is not an option, you can achieve the same via a loop:
var list = new List<bool> { true, false, true };
bool result = true;
foreach (var item in list)
{
result &= item;
if (!item)
break;
}
Console.WriteLine(result);
For small samples what you have is fine, but as the number of items grow either of the above approaches will make the code a lot friendlier.
If you must process the array and return only a single boolean, then the best approach would be to just set a value to true, then loop through until the value is false, or you reach the end of the loop.
This way you won't have to process past the first false value, since that makes the entire result false.
How you loop through depends on which version of .NET you are using.

Categories

Resources