In the following code, no matter what I try, the name strSide "does not exist in the current context", when I place a break point as shown. I want strSide to contain the last character in rawId and then to strip that character so that the value of rawId will convert to an integer. I don't get a compiler error, but do get a runtime error.
When the value of rawId is 8429R, the stripping works, but I cannot get the R assigned to strSide.
foreach (string fieldName in Request.QueryString)
{
rawId = fieldName;
String strSide = Convert.ToString(rawId[rawId.Length - 1]); <-- name does not exist
if (!IsNumeric(rawId)) <--break point set here.
{
rawId = StripRightChar(rawId);
}
Qty = Request.QueryString[fieldName];
int productId = 0;
if (fieldName == "txtReference")
{
strComments = Request.QueryString[fieldName];
}
Might the variable have been "optimized away"? It is not used anywhere after its creation. See this for details: How to prevent C# compiler/CLR from optimizing away unused variables in DEBUG builds?.
Do you need the value stored in strSide?
If not you could try this alternative solution
Update, since you need the value, try this:
var s = "8429L";
var numbers = s.Substring(0, s.IndexOfAny("RLB".ToCharArray()));
var letter = s.Substring(numbers.Length);
Related
So I have two classes.
One called 'Indexers' where I store the following strings:
class Indexes
{
public string IndexAlpha = "4uCLD[mY7^&*F_5+tXc~UrHMv1ZRxy|`3V}sjIOP<g#wT,.lnG6aK9/SJz?]bB$:8{2hfq=-0N()kd%iAe;'QEp!#>Wo"; //
public string IndexOmega = "iHL#C7(^nYzu?4$5-<cJKe~;b/XAPF_[Uf&{|m9Oolg#%]xM0REyW`jN':82Q=p6}h3kwGTZ1Vt>v,DsS.!daBri)q+*";// //
public string EncryptionCharLibrary = ",q#xRm|T=3`adV!.sDZMi)h8tb1;eKy7Yn^Q2Gwk0S]?~HL(}$4Op#g6NjU<-fAilE:%9/J[Xv>{P&zW'co+Cu5_FrB*";//
}
The other is called 'Persons' where I am running the following method..
This is called first (within the 'Persons' class):
Indexes UsingIndex = new Indexes();
Then later... v
public string InitialEncryptionComputationAndRepeatTracker() {
StringBuilder sb = new StringBuilder(Password);
int count = ForMethod.ComputeOddEven();
while (PasswordLength > 0)
{
char toFind = PasswordAsArray[PasswordLength - 1];//find first Password Char in array[0] to start
int FromAlpha = 0;
if (count % 2 == 0)
{
FromAlpha = UsingIndex.IndexAlpha.IndexOf(toFind);
}
else
{
FromAlpha = UsingIndex.IndexOmega.IndexOf(toFind);
}
char FromOmega = UsingIndex.EncryptionCharLibrary[FromAlpha];
//TEST a Character:
//MessageBox.Show("input: " + toFind + " | High/low: " + FromAlpha + " | Encryption: " + FromOmega);
char[] squiggle = { '-' };
if (toFind != squiggle[0])
{
//do nothing (subtract 1 from length down below. --v--
sb[PasswordLength - 1] = FromOmega; // store in position of StringBuilder -
FinalEncryptedPass = sb.ToString(); // Enter change into password value - <-1
//Checkfor repeat values -v-
}
int RepeatChecker = FinalEncryptedPass.LastIndexOf(toFind); //grab another instance of, and store as an integer value, the index of where that repeat character is-
while (RepeatChecker != -1) // If the value 'RepeatChecker' is 'null'/ or -1, we know that there was no repeat of the value we just changed a second ago- -1-^
{
string integerToCountBy = RepeatChecker.ToString();
AccountableToRepeats.Add(integerToCountBy); // should add a zero at the first repeat-
string toFind2 = toFind.ToString(); // Convert "the 'char' in question" to string so we can add to the string list ( AccountabletoRepeats )
AccountableToRepeats.Add(toFind2); // ex. the password 'Reed23' would have the following stored in
// AccountableToRepeats -list (ignoring encryption): AccountableToRepeats["0",1,"E",E"] before the while=looop ends.
//count = count++;// doesn't work.. just keep them in some order and replace the squiggles.
// squiggle has to be a char first to go into stringbuilder below (just like 'fromOmega' (in the instance of "none-repeating characters"))
sb[RepeatChecker] = squiggle[0];
FinalEncryptedPass = sb.ToString();
RepeatChecker = FinalEncryptedPass.LastIndexOf(toFind); //check for another repeat of the same character (stored in 'toFind' variable) // ----------------------+
}
PasswordLength = PasswordLength - 1;
count = count+ 1;
}
return sb.ToString();
}
The method is essentially supposed to use chars at specific indexes of the variables ( IndexAlpha, IndexOmega, and EncryptionCharLibrary ) from an 'Indexers' object ( UsingIndexes), however!!, when I run, I get an error within the 'Indexes.cs' class saying, exception of type 'system.stackoverflowexception' was thrown..
It sounds like, in my words, "the first variable in the Indexes.cs class is being declared until the-end-of-time".. I'm trying to reform my literally savage procedural programming ways, by essentially shuffling the code you see above over and I'm not sure if it's appropriate to be calling an object of a class within the method of another class? is that what I did wrong?
idts.. Very appreciative of any help ( I had NOT had any issues with 'Indexes.cs' throwing the overflow error until I had input the Person's method, (by it's christian name: 'InitialEncryptionComputationAndRepeatTracker()' ).
As Julo pointed out in the comments,
this is the method where the StackOverflowException was thrown, place a breakpoint on the first line of the function. Once the application breaks, try to step each function (or to simply it, press again F5). The breakpoint should stop the application again. Then see stack trace to which function calls this function from within it and fix recursion.
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.
I'm Getting a querystring data in ASP.NET C# and I need both its string value and int.Parse value of it (if it can be parsed). (in the example I'm skipping checking for null values as it has no effect on my question)
value = Request.QueryString["value"];
id = int.TryParse(Request.QueryString["value"], out id)
the code above does what I need but I just got curious if I could write it in one sentence so I tried this:
if (int.TryParse(Request.QueryString["value"], out id))) value=Request.QueryString["value"];
in this case I don't get the string value if it can't be parsed but I will get Its parsed value.
Any suggestions? I don't have a problem with my code I'm just asking out of curiosity that if it can be done in single line of code.
The almost-one-liner version would be
// id and value still need to be defined, of course!
int.TryParse(value = Request.QueryString["value"], out id)
Your code shouldn't work: if id is an int it won't be able to hold the bool coming out from TryParse.
You can this out,
int id;
string value = int.TryParse(Request.QueryString["value"], out id)) ? Request.QueryString["value"] : null;
Inline output variables are supported with C# 7.0 (released back in March '17)
var value = int.TryParse(Request.QueryString["value"], out int id) ? Request.QueryString["value"] : null;
id (output variable) will contain the parsed value or default(int)
No, you do not (want) do assignments in conditionals.
Also, if you're assigning it to value then you should utilize value for efficiency.
value = Request.QueryString["value"];
id = int.TryParse(value, out id)
Lastly, you sure about id? You're assigning it to the boolean return of TryParse, yet assigning the out to it as well. I think your code is incorrect, though you say it is good.
I would assume you mean to do this:
var value = Request.QueryString["value"];
int id = -1;
if(int.TryParse(value, out id))
/* Do work here */
You cant declare it all on one line, but if you have multiple int variables you could delclare them all on one line.
Note: if int.TryParse fails is actually sets the out parameter to 0, with out parameters it needs to be assigned before leaving the method so I guess this is why.
eg:
private void test()
{
int id, id2, id3 = int.MinValue;
string value1 = int.TryParse(Request.QueryString["value1"].ToString(), out id) ? Request.QueryString["value1"].ToString() : null;
string value2 = int.TryParse(Request.QueryString["value2"].ToString(), out id2) ? Request.QueryString["value2"].ToString() : null;
string value3 = int.TryParse(Request.QueryString["value3"].ToString(), out id3) ? Request.QueryString["value3"].ToString() : null;
}
If we change Alex's answer to use out int id we don't even need to declare id in a separate line.
int.TryParse(value = Request.QueryString["value"], out int id);
I like my own personal example for others who may need it with null checking and returning both a string and a conversion. You could move the local string variable out if you needed to.
//Sets nUnitPrice to 0 if the value entered is not a double. If null remains 0.00.
if (dgvQuote[colUnitPrice.Index, nRow].Value != null)
{
var unitPriceSubString = dgvQuote[colUnitPrice.Index, nRow].Value.ToString().Replace("$", "").Trim();//Substring local variables reduce the number of times substringing needs to be called.
nUnitPrice = double.TryParse(unitPriceSubString, out _)
? Convert.ToDouble(unitPriceSubString)
: 0.00;
}
I am finding records in datatable. If the record matches then I want to compare value in the datarow and do some operation. Please see my code below for better explanation,
foreach (DataRow row2 in dtTo.Rows)
{
DataRow[] match = dtReturn.Select("Id = " + row2["Id"]);
if (match.Length > 0)
{
if (match[0]["boolInt"] == 1) // Getting error on this line
{
match[0]["NewValues"] = "";
}
}
}
I was getting error on below line
if (match[0]["boolInt"] == 1)
Then resharper suggested me to cast to bool. so I changed above line to
if( (bool) (match[0]["bClosed"] = 1))
But when I run the project I get run time error as "Specified cast is not valid" on above line.
In immediate window I get value as 1 when I type ,
(match[0]["bClosed"]
What should i do to get rid of this error?
According this:
No there wont be null. The field is tinyint
you code should look like this (AFAIR, tinyint in SQL server matches byte in CLR):
if ((byte)(match[0]["boolInt"]) == 1)
{
}
If you know the field type, there's no need to call Convert methods. The faster way is to cast directly to that known type.
You need to convert the value to int. You can do it like this:
if (Convert.ToInt32(match[0]["boolInt"]) == 1)
But if the column contains a value that can't be casted you wil get an error.
A better aproach would be:
int number;
bool result = Int32.TryParse(match[0]["boolInt"], out number);
if (result && number == 1)
Try this:
if ((match[0]["boolInt"] as int?) == 1)
{
match[0]["NewValues"] = "";
}
if value is null or not valid int it won't cause exception, but should be handled anyways.
I was writing some code today and was mid line when I alt-tabbed away to a screen on my other monitor to check something. When I looked back, ReSharper had colored the 3rd line below grey with the note "Value assigned is not used in any execution path".
var ltlName = (Literal) e.Item.FindControl("ltlName");
string name = item.FirstName;
name +=
ltlName.Text = name;
I was confused; surely this code can't compile. But it does, and it runs too. The line "name +=" has no effect (that I could tell) on the string. What's going on here?
(Visual Studio 2008, .NET 3.5)
Notice that newlines are not special in C#. Because of the following line, the complete statement to the compiler is
name += ltlName.Text = name;
which is a valid statement (it assigns name to ltlName.Text, then append it to name.)
It's doing this:
name += ltlName.Text = name;
or to make it slightly clearer:
name += (ltlName.Text = name);
The result of the property setter is the value which was set, so it works a bit like this:
string tmp = name;
ltlName.Text = tmp;
name += tmp;
It's simpler to observe this when you've got different variables involved though, and just simple assignment as the final step rather than a compound assignment. Here's a complete example:
using System;
class Test
{
public string Text { get; set; }
static void Main()
{
Test t = new Test();
string x = t.Text = "Hello";
Console.WriteLine(x); // Prints Hello
}
}
The simple assignment rules (section 7.17.1) are used to determine the result of the expression:
The result of a simple assignment
expression is the value assigned to
the left operand. The result has the
same type as the left operand and is
always classified as a value.
So the type of ltlName.Text = name is the same type as ltlName.Text, and the value is the one that's been assigned. The fact that it's a property rather than a field or local variable doesn't change this.
In C#, newlines don't terminate statements - only semicolons do. So the following line of code is executing:
name += ltlName.Text = name;
Because whitespace is irrelevant in C#, line 3, 4 and 5 form one statement:
name += ltlName.Text = name;
As expected, the result is name concatenated to itself. So you get "namename".
obj.Text is just a property, so the line ends up converting to
//name += obj.Text = name;
obj.setText(name);
name += obj.Text;
Full source below
public class Program
{
public static void Main(string[] args)
{
MyClass obj = new MyClass();
string name = "name";
name += obj.Text = name;
Console.Write(name); //prints namename
}
}
It is affecting the string, but not until after the string is used to affect the literal on the display. As KennyTM pointed out, both lines form a single statement. Unlike VB, the carriage return doesn't end a statement in C#. The semicolon does. So what's happening here is the string is being set to the literal, and the result of that operation ("true" perhaps? or just the string itself? I don't remember) is being appended to the string.