I need a way to Parse an string into an integer value in c#. The problem is the user chosses a string from a combo box which contains strings such as "AAAAA" or "5". That means only at run time it is known if the parameter is a real string or an string which can be parsed to an integer. I tried around with reflection and have the fitting Parameter object.
ParameterInfo p = ps[i];
Type t = p.ParameterType;
I don't know how to go on from there or if it even is possible. I can't use if else statments because the program is supposed to load other interfaces with new parameters as well. So I could handle the default ones with if else statmentes but when a new interface with new Methodinfos is loaded that dos not work anymore.
I'm not usre that understood all your constraints. However you can parse string by using Int32.TryParse in case target string is not necessarily valid.
Int32.TryParse whould help you with that
To parse a string into an integer, you can use Convert.ToInt32(string_var), or any of the other conversion methods. See here for more.
Related
I have the following scenario.I am using App.config in Winforms and I have a value that is set to int (In settings). I want to use this value as a label text.
Am I correct that labels can only display string values?
This is what I have done here but not getting expected result (value to the label):
int ExclRate = Properties.Settings.Default.PriorExclTimer;
string ExclTime = ExclRate.ToString();
ExclTime = label60.Text;
PriorExclTimer is the type of the value in app.config.
I can make this work if I set the value in app.config to string, but that means I would have to convert from string to int in a much more sensitive part of the program, and I would rather not have to do that if possible. This is that line that works:
label60.Text = Properties.Settings.Default.PriorExclTimer;
I'm very new to C#, so I am really feeling my way around. Thanks...
In C# you cannot directly assign int to string. It has to always undergo conversion (either parse string to integer, or get a string out of integer).
As you say it's better to convert integer to a string for display purposes. Labels cannot directly show integer, so you will always need to convert it, or write some wrapper class if it's not enough.
Be aware that ToString() is culture specific, i.e. it will use the culture from the current thread. It might or might not be what you want. If you want InvariantCulture you can use ToString(CultureInfo.InvariantCulture).
P.S. As mentioned in the comments you can do various tricks like ExclRate + "", or in C#6 ${ExclRate}, but they are all basically converting an integer to string. I guess they all call ToString() inside.
int ExclRate = Properties.Settings.Default.PriorExclTimer;
label60.Text = ExclRate.ToString();
Code above will give you exception if PriorExclTimer is null or empty. So better you use int.TryParse to assign it to int. Not in this case, but ToString does not handle the null case, it gives exception. So you should try Convert.ToString instead.
While doing string manipulations you have to take care of culture and case (string case sensitive or insensitive)
This works for me:
int ExclRate = Properties.Settings.Default.PriorExclTimer;
label60.Text = ExclRate.ToString();
Many thanks for the insights on this topic. I will be manipulating data to and from a string a good bit for the project I am working on...
in my project "Light switch C#", I have a button which take me to a certain screen. The screen take one parameter of type string, for example "Office-Italy","Office- Germany"
My code:
enter code here
partial void HQ_Execute()
{
// Write your code here.
this.Application.ShowPart_1_SearchBalanceGreaterZero("IC-MOS");
}
now the question here is, I have 12 office and when I press the HQ (Head office) button I want my filter to be something like *. in other words I want my filter to have this value
this.Application.ShowPart_1_SearchBalanceGreaterZero("IC-MOS"||"IC-IT")
is this possible by anyhow?
Thanks a lot,
Zayed
No, a parameter can't have more than one value. So you'll need to change your method to accommodate what you need, e.g. by changing the parameter so that it's a collection of strings instead of a single string.
You could change the implementation instead, e.g. to allow you to pass "IC-MOS,IC-IT" and split it by commas - but it's clearer (IMO) to specify the values separately.
Other than what have been already mentioned in Jon's answer; you can pass your value as a single string and in destination method break and parse them accordingly. Something like
this.Application.ShowPart_1_SearchBalanceGreaterZero("IC-MOS|IC-IT")
In your method body
void ShowPart_1_SearchBalanceGreaterZero(string data)
{
string[] strarr = data.Split('|');
//now use the data string array the way you want
}
So, I have a valid GUID string below
Guid.Parse("e6f85ae0-f479-4e98-9287-98f7e62ba083") // Parses just fine
This parses to a GUID in .NET4.0 / 4.5
However this code
// Copy paste this line in VS Immediate window. Does not parse!!
Guid.Parse("e6f85ae0‐f479‐4e98‐9287‐98f7e62ba083")
Does not parse. The Guid strings are identical, or so I thought. Try it, in the immediate window of Visual Studio, the first does not parse, but second one does!
You can also verify with this code
var string1 = "e6f85ae0-f479-4e98-9287-98f7e62ba083";
var string2 = "e6f85ae0‐f479‐4e98‐9287‐98f7e62ba083";
bool isSame = string1.Equals(string2); // Equals false!! :/
Could this be an encoding issue? Is there any way to detect this issue and correctly parse the GUID?
I'm half convinced this is a trolling question, but in case it is an honest problem:
Those strings are not identical. the second one uses the so called 'narrow hyphen' ('\u2010'), which is a completely different character than the regular hyphen ('\u002D') and as such it is not parsed correctly.
As decPL already said the the strings are not identical due to different hyphens used, So Guid.Parse will definitely fail. To detect that the GUID is computer readable you can use Guid.TryParse Method.
bool isValidGUID = Guid.TryParse(string2, null);
And there is nothing called human readable If you are going to replace 'narrow hyphen' then in case it contains some other symbol your code will fail.
Instead of using workaround I suggest you the debug the cause for getting the 'narrow hyphen'
GUID also supports various formats. If you want to validate a specified format then you can use Guid.TryParseExact Method.
I Have my regex in a SQL Database
for example: ^[A-Z Ñ\s\.\,\\"\%]+$
Then, i get it with a SQL Reader
sql.Reader["Regular_Expression"].ToString()
But, that return the following: "^[A-Z Ñ\\s\\.\\,\\\\"\\%]+$"
Anyone know how to avoid the .ToString() function to change the string, like when you use #.
I think you're actually being led astray by the tools here. When you view the result in a Watch window in Visual Studio, it escapes any characters in the display in the same way as a regular quoted string, so you get doubled backslashes. If you actually output it somewhere, for example using System.Diagnostics.Debug.WriteLine, you shouldn't see the doubled backslashes.
When you access a column through SqlDataReader's indexer property, the return type is object. That's because it doesn't know at compile time what type it is. If the column is a string type (e.g. varchar), the returned object will be a SqlString structure, and you can cast that to string rather than calling ToString.
To solve it you've to use Regex.Unescape() function from the Regex Library.
The problem is caused to a bad casting from object to string.
Math.Round((ClosePrice - OpenPrice), 5) = -0.00001
But When I convert it into tostring it gives "-1E-05"
Math.Round((ClosePrice - OpenPrice), 5).ToString() = "-1E-05"
Why this is so ? How can I get "-0.00001"
You can use format specifier as demonstrated on MSDN's Standard Numeric Format Strings
double foo = -0.00001;
Console.WriteLine(foo.ToString("f5"));
ToString() chooses a format based on the value being formatted to achieve the most compact representation. If you would like to choose a specific format, you need to use the ToString(string format) overload instead. For example, if you call
Math.Round((ClosePrice - OpenPrice), 5).ToString("N5")
you will get "-0.00001" string as the result.
Every class inheriting from object (and therefore any class) has a .ToString() method. What it outputs depends on weather it was overwritten and if it was, how it was overwritten (i.e. what did the implementer want to give out as string. Its the same process you would go through if implementing a .ToString() method for one of your classes.
This is as to "Why" - the "How" has been answered by others.