I am working on a basic Battleship game to help my C# skills. Right now I am having a little trouble with enum. I have:
enum game : int
{
a=1,
b=2,
c=3,
}
I would like the player to pass the input "C" and some code return the integer 3. How would I set it up for it to take a string var (string pick;) and convert it to the correct int using this enum? The book I am reading on this is bit confusing
Just parse the string and cast to int.
var number = (int)((game) Enum.Parse(typeof(game), pick));
// convert string to enum, invalid cast will throw an exception
game myenum =(game) Enum.Parse(typeof(game), mystring );
// convert an enum to an int
int val = (int) myenum;
// convert an enum to an int
int n = (int) game.a;
just typecasting?
int a = (int) game.a
If you're not sure that the incoming string would contain a valid enum value, you can use Enum.TryParse() to try to do the parsing. If it's not valid, this will just return false, instead of throwing an exception.
jp
The answer is fine but the syntax is messy.
Much neater is something like this:
public DataSet GetBasketAudit(enmAuditPeriod auditPeriod)
{
int auditParam =Convert.ToInt32(auditPeriod) ;
Related
I want to convert string to int but some time is not working.
Here is my code:
public static int ToInt(String pStr)
{
return Convert.ToInt32(Microsoft.VisualBasic.Conversion.Val(pStr));
}
Int i = ToInt("F0005");
Output is 0 - it works fine.
But when I pass in a value like this
Int i = ToInt("E0305");
Then I get an error "Out-of-range exception".
I have a mix of values, some are int and some are strings; I want to pass each and every value in loop and convert it to int, but when I pass this value then I get an error.
If you just want to skip invalid string value, it is better to use TryParse instead of returning 0 (which might be valid value). At your calling code it should look like this:
string val = "F0005";
if (int.TryParse(val, out int i) {
// parse success. you can use i here
}
else {
// parse failed.
}
If you really want it to be 0, this should work
string val = "F0005";
int i = int.TryParse(val, out int x) ? x : 0;
You can do it in C# alone without VB.NET library
public static int ToInt(string pStr)
{
return int.Parse(pstr);
}
Noted that this will throw exception if pStr is not a valid integer string. In your case, it might also throw exception if the value is too big, which you might need long instead to hold bigger numbers.
public static long ToInt64(string pStr)
{
return long.Parse(pstr);
}
Also, I just noticed that you are trying to parse "E0305" which is not really a valid format (as far as I know). The closest one is "1E305", which means 1 with 305 zeroes afterward. If you need to parse an integer that big, you might need BigInteger
public static BigInteger ToBigInteger(string pStr)
{
return BigInteger.Parse(pstr, System.Globalization.NumberStyles.AllowExponent);
}
The System.Globalization.NumberStyles.AllowExponent part is there to allow parsing the number in exponent representation.
Try using int.TryParse() method for those cases where you have some unexpected and you do not want exceptions in proces of parsing them.
Use case for it would be:
var isValid = int.TryParse(pStr, out int result);
Also another benefit of using it is that you have return value that provides you a way to handle unsuccessful parsing call.
What is the C# equivalent of:
Public stringValue As String
Public intValue As Integer
intValue = Format(val(stringValue), "00")
?
So the vb6 Format function converts to string and the Val function converts to a number. If you look at the Microsoft documentation for Val:
Val(" 1615 198th Street N.E.")
// returns
1615198
in c# this can clumsily be converted to
string stringValue = " 1615 198th Street N.E.";
// assign to int if int wanted
// throws exception if cannot be converted to int, use Int32.TryParse if you want to handle that
int intValue = System.Convert.ToInt32(
new string(stringValue.Replace(" ", "").TakeWhile(System.Char.IsDigit).ToArray())
);
System.Console.WriteLine(intValue);
it's really going to depend on what your expectations are for what stringValue is going to be and what you want returned. Also I don't think you can assign a string value to an int so willy nilly like you can in vb6. It can definitely be cleaned up but that just depends on what you're doing.
edit:
Since you're testing a stringValue = "3" this should work
string stringVal = "3";
if(!System.Int32.TryParse(stringVal, out int intValue))
{
System.Console.WriteLine($"value={stringVal} not of type int");
}
return intValue;
If truly replicating the VB6 Val function is desired, then Microsoft.VisualBasic.Val can be used. It is pretty faithful to the original, and of course can be called from C#.
See https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.conversion.val?view=netcore-3.1#Microsoft_VisualBasic_Conversion_Val_System_String_ for the string overload (returns Double).
One aspect where it doesn't return the same result as VB6 is for a string like "3.4.5". VB6 Val will return 34.5, while the .Net Val will return 3.4.
No need for exception handling (just like with VB6), if the input can't be converted to a number, no exception is thrown (well, mostly, there are some edge cases) or error returned, the return value is zero.
For example, I have declared the following enum in C#.
C# code:
public enum LobMaster :int
{
RetailBroking = 1,
HNI = 2,
TechnologyInfrastructure = 3,
}
cshtml code:
#int code = 2
#if (LobMaster.RetailBroking == code)
{
}
If I try to compare int enum with integer value it gives me following error message.
operator '==' cannot be applied to types 'LobMaster' and 'int'
While my enum
LobMaster
is already an int type.
But when I cast the enum to int and then compare with int value it works fine.
So my question is why I need to cast enum to int as enum is already an int.
The main purpose of Enums is to remove "magic numbers", so you should ask yourself - why do you want to use those magic numbers?
Much better comparison would be:
Session["Lob_code"] is LobMaster && LobMaster.MassAffluent == (LobMaster)Session["Lob_code"]
This way you are avoiding those magic numbers and your code just provides all the context.
#if ((int) LobMaster.MassAffluent == Convert.ToInt32(Session["Lob_code"])) { }
you should be able to cast the left hand value and then do the conoarison
I have defined an enum and tried to retrieve it as follows
class Demo
{
enum hello
{
one=1,
two
}
public static void Main()
{
Console.WriteLine(hello.one);
Console.ReadLine();
}
}
Now, how do i retrieve the integer value "1" from the enum ?
There's an explicit conversion from any enum type to its underlying type (int in this case). So:
Console.WriteLine((int) hello.one);
Likewise there's an explicit conversion the other way:
Console.WriteLine((hello) 1); // Prints "one"
(As a side note, I'd strongly advise you to follow .NET naming conventions, even when writing tiny test apps.)
you can cast the enums like
int a = (int)hello.one
Well you can do a cast to int
Console.WriteLine((int)hello.one);
Try This.
Console.Writeline((int)hello.Value);
or
int value = Convert.ToInt32(hello.one);
This is probably trivial, but I can't think of a better way to do it. I have a COM object that returns a variant which becomes an object in C#. The only way I can get this into an int is
int test = int.Parse(string.Format("{0}", myobject))
Is there a cleaner way to do this? Thanks
You have several options:
(int) — Cast operator. Works if the object already is an integer at some level in the inheritance hierarchy or if there is an implicit conversion defined.
int.Parse()/int.TryParse() — For converting from a string of unknown format.
int.ParseExact()/int.TryParseExact() — For converting from a string in a specific format
Convert.ToInt32() — For converting an object of unknown type. It will use an explicit and implicit conversion or IConvertible implementation if any are defined.
as int? — Note the "?". The as operator is only for reference types, and so I used "?" to signify a Nullable<int>. The "as" operator works like Convert.To____(), but think TryParse() rather than Parse(): it returns null rather than throwing an exception if the conversion fails.
Of these, I would prefer (int) if the object really is just a boxed integer. Otherwise use Convert.ToInt32() in this case.
Note that this is a very general answer: I want to throw some attention to Darren Clark's response because I think it does a good job addressing the specifics here, but came in late and wasn't voted as well yet. He gets my vote for "accepted answer", anyway, for also recommending (int), for pointing out that if it fails (int)(short) might work instead, and for recommending you check your debugger to find out the actual runtime type.
The cast (int) myobject should just work.
If that gives you an invalid cast exception then it is probably because the variant type isn't VT_I4. My bet is that a variant with VT_I4 is converted into a boxed int, VT_I2 into a boxed short, etc.
When doing a cast on a boxed value type it is only valid to cast it to the type boxed.
Foe example, if the returned variant is actually a VT_I2 then (int) (short) myObject should work.
Easiest way to find out is to inspect the returned object and take a look at its type in the debugger. Also make sure that in the interop assembly you have the return value marked with MarshalAs(UnmanagedType.Struct)
Convert.ToInt32(myobject);
This will handle the case where myobject is null and return 0, instead of throwing an exception.
Use Int32.TryParse as follows.
int test;
bool result = Int32.TryParse(value, out test);
if (result)
{
Console.WriteLine("Sucess");
}
else
{
if (value == null) value = "";
Console.WriteLine("Failure");
}
Maybe Convert.ToInt32.
Watch out for exception, in both cases.
var intTried = Convert.ChangeType(myObject, typeof(int)) as int?;
I am listing the difference in each of the casting ways. What a particular type of casting handles and it doesn't?
// object to int
// does not handle null
// does not handle NAN ("102art54")
// convert value to integar
int intObj = (int)obj;
// handles only null or number
int? nullableIntObj = (int?)obj; // null
Nullable<int> nullableIntObj1 = (Nullable<int>)obj; // null
// best way for casting from object to nullable int
// handles null
// handles other datatypes gives null("sadfsdf") // result null
int? nullableIntObj2 = obj as int?;
// string to int
// does not handle null( throws exception)
// does not string NAN ("102art54") (throws exception)
// converts string to int ("26236")
// accepts string value
int iVal3 = int.Parse("10120"); // throws exception value cannot be null;
// handles null converts null to 0
// does not handle NAN ("102art54") (throws exception)
// converts obj to int ("26236")
int val4 = Convert.ToInt32("10120");
// handle null converts null to 0
// handle NAN ("101art54") converts null to 0
// convert string to int ("26236")
int number;
bool result = int.TryParse(value, out number);
if (result)
{
// converted value
}
else
{
// number o/p = 0
}
There's also TryParse.
From MSDN:
private static void TryToParse(string value)
{
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
}
Strange, but the accepted answer seems wrong about the cast and the Convert in the mean that from my tests and reading the documentation too it should not take into account implicit or explicit operators.
So, if I have a variable of type object and the "boxed" class has some implicit operators defined they won't work.
Instead another simple way, but really performance costing is to cast before in dynamic.
(int)(dynamic)myObject.
You can try it in the Interactive window of VS.
public class Test
{
public static implicit operator int(Test v)
{
return 12;
}
}
(int)(object)new Test() //this will fail
Convert.ToInt32((object)new Test()) //this will fail
(int)(dynamic)(object)new Test() //this will pass
You can first cast object to string and then cast the string to int;
for example:
string str_myobject = myobject.ToString();
int int_myobject = int.Parse(str_myobject);
this worked for me.
int i = myObject.myField.CastTo<int>();
This worked for me, returning 0 also when myobject contains a DBNull
int i = myobject.ToString().Cast<int>().FirstOrDefault();