Given an enum like:
enum Test
{
Hi=0x1,
Hello=0x2
}
From the database, I get either a 1 or 2.
I need to concatenate 0x (to display as hex value), when the query returns 1.
I concatenate 0x and when I assign, I get an invalid argument exception.
(Test)Enum.Parse(typeof(Test), reader.GetString(0));
How can this be done?
Test = (Test)int.Parse(reader.GetString(0));
That's bare minimum code, you need to do error checking and all that good stuff.
I am not sure what you are looking to do, but if you want to convert a string value in a database that is "0x0" or "0x1", then you can use something like the code below for t1 & t3:
Test t1 = (Test) Enum.Parse(typeof (Test), Convert.ToInt32("0x0", 16).ToString());
Test t2 = (Test) Enum.Parse(typeof(Test), "0");
Test t3 = (Test) Enum.Parse(typeof(Test), Convert.ToInt32("0x1", 16).ToString());
Test t4 = (Test) Enum.Parse(typeof(Test), "1");
Well, there's always Enum.TryParse. If you're not on .NET 4.0 yet, implementing a similar method for your own use only requires a few steps:
static bool TryParseEnum<TEnum>(string text, out TEnum value)
{
value = default(T);
int number;
if (int.TryParse(text, out number) && Enum.IsDefined(typeof(TEnum), number))
{
// This awkward double-cast is unfortunately necessary
// due to the lack of a where T : enum constraint --
// the compiler cannot guarantee that T is castable from int.
value = (TEnum)(object)number;
return true;
}
return false;
}
However, based on the answer you've accepted, it seems I may have misinterpreted your question! Nevertheless, I am leaving this answer here in case it's useful to anyone.
I think what you're trying to do is this:
Take a a string representation of a decimal number, and display that
number in hexidecimal form.
If so, try this:
String x = String.Format("{0:X2}", Int.Parse(myInteger));
Or perhaps I've misunderstood what your problem is.
Related
I just want to know, whether a variable contains a positive integer value.
Currently I am doing:
int APPOeeVersion =
Convert.ToInt32(ConfigurationManager.AppSettings["OEEVersion"]);
Here i just want to know whether APPOeeVersion Contains Int value or not. If not Need to show a error message as it is invalid format. Please help me out i have checked with several forums but not find exact solution.
Use int.TryParse, It will not raise an exception in case of failure and would give you bool value back if parsing was successful/unsuccessful.
string str = "1234";
int APPOeeVersion;
if (int.TryParse(str, out APPOeeVersion))
{
//parsing successful
}
else
{
//not an integer
}
If parsing is successful you will get the value of parsed string in your out parameter.
For checking a positive number and parsing you can have the check like:
if (int.TryParse(str, out APPOeeVersion) && APPOeeVersion > 0)
If you want to test for a positive integer, then you might need to use uint.TryParse since int.TryParse will allow negative values.
uint appoEeVersion;
var oeeVersionValue = ConfigurationManager.AppSettings["OEEVersion"];
if(!uint.TryParse(OEEVersionValue , out appoEeVersion))
{
// Error, not a positive integer
}
else
{
// Success, user value
}
int.TryParse would be the method: http://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx
int APPOeeVersion;
if(!int.TryParse(ConfigurationManager.AppSettings["OEEVersion"], out APPOeeVersion) || APPOeeVersion < 0){
//throw error
}
//use variable APPOeeVersion
I'm a little confused by your wording. Do you mean the variable is an integer or contains an integer?
If the former, then the solutions posted will work fine.
Are you guaranteed that the variable will only ever be an integer with no decimal notation (eg: 2 vs 2.0)? If not, you might need to use decimal.parse instead.
Integer parsing will fail on the other decimal values since they are not valid integers.
Decimal APPOeeVersion;
if (Decimal.TryParse(input,out APPOeeVersion))
{
Console.WriteLine("Successfully parse: {0} to {1}", input, APPOeeVersion);
}
else
{
Console.WriteLine("Failed to parse {0}", input);
}
Console.Write("\nEnter a number to test: ");
Then then use additional logic to ensure that the result is positive.
If you want to know whether it contains an integer, then a regular expression like the ones found here will work.
Maybe I'm just dumb or overthinking this, but it seems like you have to give a few more constraints
In my code i try to get browser version for charging the good css file, but this code doesn't work, and i don't see my error...
I've simply try first with a Convert.ToInt32 but don't works too...
public ActionResult Index()
{
ViewBag.logged = false;
ViewBag.BrowserName = Request.Browser.Browser.ToString();
Int32 v = 0;
string version = Request.Browser.Version;
if (version != null)
{
bool result = Int32.TryParse(version, out v);
}
ViewBag.BrowserVersion = v;
return View();
}
In my debugger :
version => string : "23.0"
v => int 0
result => false
Request.Browser.Version => string "23.0"
This is by design.
Parsing a version string would work better with System.Version.
You can, alternatively, parse it to a float and then see if a lossless conversion to Int32 can be made.
I fully agree with Andrei's answer; that's the approach you should take.
However, I think it's important to note that there is a way to parse int values from strings such as "23.0": it can be done using this overload of int.TryParse() which allows you to pass NumberStyles flags as parameters.
Concretely, after executing this code:
int v;
var wasParsedOK = Int32.TryParse(
"23.0",
NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture,
out v);
v will hold the value 23 and wasParsedOK will be true.
You can't assume that the version string is going to be integral, or even decimal. A browser could perfectly report 7.0b as its version. None of int, float, decimal or System.Version can represent this.
If you're only concerned about the major and minor version numbers, you can use the MajorVersion and MinorVersion properties of your Browser object, assuming it is of type HttpBrowserCapabilities. The framework has done the parsing for you, so it should be reliable.
It is giving false because 23.0 is not an int, So you can try with decimal,double or float.
decimal v = 0;
string version = "23.0";
Decimal.TryParse(version, out v);
It's been almost 2 years and no one has answered this correctly. The question is simple, "Why is it returning false?"
This question has already been answered, simply because your string is not an Integer, but is a Double or Decimal. By design, TryParse will try to get the EXACT match of the type integer from your string, if not it will return false, and your string ("23.0") is not an exact match.
Now if you're trying to find a solution in converting your version string to a number, What you can do is filter out the non-numeric, excluding 1 dot (.), in the string, then convert what's left to decimal/double. After this conversion you can then try converting it integer. Since you already converted your stirng to double/decimal, you can no longer use TryParse because the parameter needs to be in string format. You can then use Convert.ToInt32 inside a Try block.
Sometimes i wonder, when converting strings to other types, for example int32, is one way better than the other, or is it just a matter of taste?
Convert.ToInt32("123")
or
Int32.Parse("123")
or
Some other way?
Not considering the case if it's not a valid int in this question.
The Convert.ToInt32 is actually implemented the following way...
int.Parse(value, CultureInfo.CurrentCulture);
...which is the same as your stated alternative except it takes into account the culture settings. The int.Parse method is itself implemented the following way...
Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
...where Number is an internal class that you cannot call directly. The Number.ParseInt32 method is marked with the following attribute...
[MethodImpl(MethodImplOptions.InternalCall)]
...showing that it is implemented inside the CLR itself.
Main difference between Conver.ToInt32 and Int32.Parse is how the treat null strings. Convert.ToInt32 returns default value in this case:
public static int ToInt32(string value)
{
if (value == null)
return 0;
return Int32.Parse(value, CultureInfo.CurrentCulture);
}
I don't like that. I think only "0" should be parsed to 0. This behavior initially was designed for Visual Basic programmers:
This is a set of conversion methods for programmers migrating from Visual Basic 6 to Visual Basic .NET that mirrored the behavior of the
existing Visual Basic 6 conversion methods. The assumption was that C#
programmers would be more comfortable with casting operators, whereas
Visual Basic had traditionally used conversion methods for type
conversion.
So, as non-VB programmer, I'd go with Int32.Parse and Int32.TryParse.
When converting from string to int I always use int.TryParse. Because you are not always sure you can convert a string to an int. Like this:
string temp="222";
int intValue;
if(int.TryParse(temp,out intValue))
{
//Something
}
As V4Vendetta suggested it is better to use TryParse to avoid exceptions related to converting.
int result = 0;
a = "3";
string b = "b";
string c = "2147483648"; //int32 max value + 1
int.TryParse(a, out result); // returns true result=3
int.TryParse(b, out result); // returns false result=0
int.TryParse(c, out result); // returns false result=0
I've been investigating the out keyword in C# after reading the section about it in C# in Depth. I cannot seem to find an example that shows why the keyword is required over just assigning the value of a return statement. For example:
public void Function1(int input, out int output)
{
output = input * 5;
}
public int Function2(int input)
{
return input * 5;
}
...
int i;
int j;
Function1(5, out i);
j = Function2(5);
Both i and j now have the same value. Is it just the convenience of being able to initialize without the = sign or is there some other value derived that I'm not seeing? I've seen some similar answers mentioning that it shifts responsibility for initialization to the callee here. But all that extra instead of just assigning a return value and not having a void method signature?
Usually out is used for a method that returns something else, but you still need to get a different value from the method.
A good example is Int32.TryParse(input, out myVar) it will return true if it was successful and false otherwise. You can get the converted int via the out parameter.
int myOutVar;
if (Int32.TryParse("2", out myOutVar))
{
//do something with the int
}else{
//Parsing failed, show a message
}
The out / ref keywords in C# should only be used when you need to return multiple values. Even then you should first consider using a container type (such as Tuple) to return multiple values before you revert to out / ref. Whenever you're returning a single value it should just be returned.
A lot of times, using out can help by giving you a slight performance gain.
Consider the TryGetValue method on IDictionary (say myDictionary is an IDictionary<string, string>) Rather than doing this:
string value = String.Empty;
if (myDictionary.ContainsKey("foo"))
{
value = myDictionary["foo"];
}
Both ContainsKey and the indexer need to look up the key in the dictionary, but you can avoid this double-lookup on the positive case by going:
string value;
if (!myDictionary.TryGetValue("foo", out value))
{
value = String.Empty;
}
IMO, that's a decent reason for using out parameters.
Unfortunately we cannot do something like below in C#:
a,b = func(x,y,z);
something that we do in Python or other languages. out kind of overcomes that.
F# has overcome this with tuples I believe.
PS: Returning multiple values from a function might not be good always. Tiny types are good most of the times - http://www.martinfowler.com/bliki/DataClump.html
For example, Int32.TryParse returns boolean if it parsed correctly and with the out parameter changes the value. If the parsed value is 0 and it returns true it means the value you sent to parse was 0. If it returns false then the parser failed.
Some of it is for clarity. Take the TryParse() methods, like
Int32.TryParse("3", out myInt);
This returns a bool that indicates whether the string was able to be parsed into an int.
If you just had
Int32.TryParse("3", myInt);
What happens when that's called? Is myInt assigned? Does TryParse return an int?
It's not readily apparent. But if I have an out parameter, then I know that the value is getting assigned, and that the return is something else.
Basically you do something like (my database read)
if (ReadSingle<UserRecord>(cmd, out user))
Cache.Insert(cacheId, user, null,
DateTime.MaxValue, TimeSpan.FromMinutes(3));
Or else you do something like:
user = ReadSingle<UserRecord>(cmd);
if(null != user)
// Cache.Insert ...
It simplifies the code a little to use a boolean result (that a record was read from the database) and get the actual record into the variable via the out keyword.
I have the following variables:
string str1 = "1";
string str2 = "asd";
string str3 = "3.5";
string str4 = "a";
Now I need to find the data type of each string i.e. the data type to which it can be converted if quotes are removed. Here is what I would like each variable to convert to:
str1 - integer
str2 - string
str3 - double
str4 - char
Note: if the string has single character it should be char, though a string can have single letter, I'm limiting it.
FYI: these values are obtained from DataGrid where i manually entered values. So everything is becoming a string.
Is there any way to do this?
Of course, there's no definite way to do this, but if you create a list of data types you want to check ordered by priority, then something like this may do the trick.
object ParseString(string str)
{
int intValue;
double doubleValue;
char charValue;
bool boolValue;
// Place checks higher if if-else statement to give higher priority to type.
if (int.TryParse(str, out intValue))
return intValue;
else if (double.TryParse(str, out doubleValue))
return doubleValue;
else if (char.TryParse(str, out charValue))
return charValue;
else if (bool.TryParse(str, out boolValue))
return boolValue;
return null;
}
Just call this function on each string, and you should have the appropiate type of object returned. A simple type check can then tell you how the string was parsed.
Use meta-data, if you can
That you have to guess what the data types are, is not a good idea.
Two things
1 Where is the data coming from?
If it's a database, are you sure they're strings?
If it is a database, there should be some meta data returned that will tell you what the datatypes of the fields are.
If it's an Xml file, is there a schema defined that will give you the types?
2 If you have to continue to guess.
Be aware that you can have strings that happen to be numbers, but are perfectly valid strings e.g phone numbers, bank acount numbers, that are best expressed as strings.
Also these numbers can have many digits, if you convert them to doubles you may loose some digits to floating point inaccuracies (you should be OK up to 14 or 15 digits)
I'm sure by now - cause I've taken my time typing this - there are lots of answers telling you how to do this (i.e. tryparse int first, then double, then test length for char, if not then it's a string etc), but if I were you, I'd try to NOT do that, and see if there's any way you can get, or pass some meta-data that will tell you what type it IS and not just what type it might be
Use the TryParse method of each type.
There is no built in way to do this, you could attempt TryParse on number types with increasing precision, but it wouldn't guarantee it to be right.
Your best bet what be to process it like you would manually. i.e. Is there a decimal place? No - then its an integer. How big? Is it negative?
The datatype for each of these items is string. If you want to attempt to parse them into different types you can use Int32.TryParse, Double.TryParse, etc. Or you can use Regex:
bool isInt = new Regex(#"^\d+$").IsMatch(str);
bool isDouble = !(isInt) && new Regex(#"^\d+\.\d+$").IsMatch(str);
bool isChar = !(isInt || isDouble) && new Regex(#"^.$").IsMatch(str);
bool isString = !(isInt || isDouble || isChar);