I have a problem with my winforms application and I didn`t find a way to solve it: I am running a while loop which is fetching a value from a webserver.
Then this value should be substracted from the value which was fetched by the loop the run before.
while(true)
{
valuecurrent = webclient.DownloadString("http://ipadress/value");
double result = (valuebefore - valuecurrent);
}
Is there a way to save the value from the run before and use it in the next run of the loop?
Thanks in advance!
Tim
Just add a variable outside/before the loop and set it on each pass.
var valuebefore = 0;
while(true)
{
valuecurrent = webclient.DownloadString("http://ipadress/value");
double result = (valuebefore - valuecurrent);
valuebefore = valuecurrent;
}
// Assign a null value before
double? valuebefore = null;
while (true)
{
// Get the current value from the webserver
valuecurrent = webclient.DownloadString("http://ipadress/value");
// Use the current value if we don't have any previous values
// Subtract the current value from previous value if it exists
double result = valuebefore.HasValue == false
? valuecurrent
: valuebefore.Value - valuecurrent;
// Save the result to our value before to be used in next loop
valuebefore = result;
}
You can leverage nullable types and a simple if/then logic to save the first value then subtract subsequent values.
Related
I got simple problem, but couldn't find solution:
Is it possible to check if given variable has been assigned?
int i;
// stuff happens
if (someTest(i));
i = 0;
Console.Write("now i is assigned for sure")
For value types, the variable is always assigned. There is a value there of some kind. Even so, if you try to read the variable before it is assigned the compiler will tell you and show an error: your code will not compile.
In case of you need to know given field set or not, you can have Property to control that field. in the setter you can control it, for example in below example isSet Boolean flag is updated when the value set. if you need to reset the flag based on another value you can add another condition in the setter.
private int i;
private bool isSet;
public int IProp
{
get { return i;}
set { isSet =true; i=value; }
}
// test
Console.WriteLine("Is Set:" + isSet);
IProp = 0;
Console.WriteLine("Is Set:" + isSet);
//results
//Is Set:False
//Is Set:True
I am trying to read some decimal values from my DB. These values are the order of 10-6. I am trying to read it into a double variable in C# using code like this: sqltype in database is "float". sample value to be read is "1.99999999495049E-06" –
Double [] rmseValues = null;
while (dataReader.Read())
{
// This shows my datatype is float (sql)
string temp = dataReader.GetDataTypeName(0);
// This returns a value of "0"
string temp1 = dataReader.GetOrdinal("RmseAll").ToString();
// This throws exception of invalid typecast
rmseValues[0] = dataReader.GetFloat(0);
}
Try to use GetDouble(0) instead of GetFloat(0)
I think you will also need to edit that line :
Double [] rmseValues = null;
In fact your are trying to put values inside a null object as solution you need to initialize your rmseValues array or just use a List of double
Double[] rmseValues = new Double[10];
Use GetInt64(0) instead of GetFloat(0)
In order not be dependent on RDBMS actual background type (say, NUMBER(10, 3) or alike) and its representation as .Net Type (e.g. Single) do a conversion:
// rmseValues[0] should be Double
rmseValues[0] = Convert.ToDouble(dataReader.GetValue(0));
the problem I'm having is to validate the input means putting it in a try catch which then wont pass the variable through and I'm getting this error:
Use of unassigned local variable 'MainMenuSelection'
I've validated using this method before but for some reason it's not working now, please help
//Take the menu selection
try
{
mainMenuSelection = byte.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Please enter a valid selection");
}
switch (mainMenuSelection) //Where error is shown
Obviously user can input anything which would not be parsed as a single byte. Try out using Byte.TryParse() method which does not generate exception and just return status flag.
You can go further and add more analysis for an user input if needed:
// Initialize by a default value to avoid
// "Use of unassigned local variable 'MainMenuSelection'" error
byte mainMenuSelection = 0x00;
string input = Console.ReadLine();
// If acceptable - remove possible spaces at the start and the end of a string
input = input.Trim();
if (input.Lenght > 1)
{
// can you do anything if user entered multiple characters?
}
else
{
if (!byte.TryParse(input, out mainMenuSelection))
{
// parsing error
}
else
{
// ok, do switch
}
}
Also perhaps you just need a single character not a byte?
Then just do:
// Character with code 0x00 would be a default value.
// and indicate that nothing was read/parsed
string input = Console.ReadLine();
char mainMenuSelection = input.Length > 0 ? input[0] : 0x00;
A better method would be to use byte.TryParse(). It's made specifically for these types of scenarios.
byte b;
if (byte.TryParse("1", out b))
{
//do something with b
}
else
{
//can't be parsed
}
If you're just concerned about the input itself, you can use the Byte.TryParse Method and then handle the false boolean case instead.
byte mainMenuSelection;
if (Byte.TryParse(Console.ReadLine(), out mainMenuSelection)
{
switch(mainMenuSelection);
}
else
{
Console.WriteLine("Please enter a valid selection");
}
Using C# in ASP.NET, I want to take the result of two text fields, add them when a button is pressed, and display the result. However, if one or both of the fields are empty, I don't want any result shown.
Right now I keep getting 0 as the result if both fields are empty. I'm pretty sure this is because the two input numbers (doubles) are being assigned a default 0. How can I check for empty fields?
This is my method in my controller.
[HttpPost]
public ActionResult French(FrenchModel model, string returnUrl)
{
switch (model.operation)
{
case 1:
model.result = model.numberOne + model.numberTwo;
break;
case 2:
model.result = model.numberOne - model.numberTwo;
break;
case 3:
model.result = model.numberOne * model.numberTwo;
break;
case 4:
model.result = model.numberOne / model.numberTwo;
break;
}
return View(model);
}
Doubles are value types and thus cannot be assigned to null or "empty". If you want this capability, try using a nullable double. Either Nullable<double> or double? should work.
Be aware, using a nullable value type you will need to check it for null before you use it or risk a NullReferenceException whereas double defaults to 0 if unassigned.
Use Double? ie nullable Double, its default value is null and you'll assign a value only if textbox is not empty and you can parse it.
Here's one way to determine if one or both of the fields are empty. Refactor as you need with your particular variables.
string one = txt1.Text;
string two = txt2.Text;
string result = (string.IsNullOrEmpty(one) || string.IsNullOrEmpty(two))
?string.Empty
:double.Parse(one) + double.Parse(two);
You can use if statements:
if (operand1 != 0) { // do something.. }
else { // do something.. }
You can also do this for the second operand
Hi in my opinion property of my object shouold be 2, but after this code, is still 1, why?
internal class Program
{
private static void Main(string[] args)
{
MyClass value = new MyClass() { Property = 1 };
value.Property = value.Property++;
Console.WriteLine(value.Property);
Console.ReadKey();
}
}
internal class MyClass
{
public int Property;
}
in my opinion this should value.Property = value.Property++; first put to value what is in value and the increment property of this object, why id doesn't work?
What this does is:
Evaluate value.Property on the right hand side (result is 1) and remember the result
Increment value.Property (now it's equal to 2)
Assign the remembered result to value.Property (it's now again equal to 1!)
If you change Property to a property with an explicit getter and setter and put some debugging code inside the setter, you will see that it does indeed change values 1 -> 2 -> 1.
If you changed value.Property++ to ++value.Property, the first two steps would be reversed, so we 'd have:
Increment value.Property (now it's equal to 2)
Evaluate value.Property on the right hand side (it's still 2)
Assign the result of step 2 to value.Property (it's still 2)
Of course, this is unnecessarily complicated and one could even say, wrong. If you want to increment Property, all you have to do is this:
++value.Property;
Because valueProperty++ is the same as the following:
int Increment(ref int value)
{
var temp = value;
value = value + 1;
return temp;
}
value.Property = value.Property++;
Here value.Property++ means it assing 1 before incrementing.
Because the = operator is lower down the order of operator precedence than increment.
http://msdn.microsoft.com/en-us/library/6a71f45d.aspx <- shows al the operators and their order of precedence.
The increment gets evaluated first completely. then the returned value from the increment is put through the = operator.