I am using an enum as my options for a switch statement and it works. The problem is if the user enter a non valid option the program crashes. What should I add so that the default is used?
my enum class
public enum Options : byte
{
Display = 1,
Add,
Toggle,
Max,
Mean,
Medium,
Exit
}
in main my switch statement
string volString = Console.ReadLine();
Options options = (Options)Enum.Parse(typeof(Options), volString);
// this is the line that is giving me the runtime error. Since other options are not found
in the enum the program crashes.
switch (options)
{
case Options.Display: //dispaly regular time
case Options.Toggle://toggle
default:
Console.WriteLine("entry blah blah");
break;
Instead of Enum.Parse use Enum.TryParse... this will return a boolean to say if the text can be converted into your enum. If it's true run your switch otherwise inform the user that they entered an invalid string.
Use Enum.TryParse instead:
Options options;
if(!Enum.TryParse(volString, out options)) {
// It wasn't valid input.
}
How about:
Options value;
if(!Enum.TryParse(volString, out value)) // note implicit <Options>
value = Options.SomeDefaultValue;
Look at Enum.TryParse(...) you can use this to check for invalid strings.
Related
This question already has answers here:
Convert a string to an enum in C#
(29 answers)
Closed 3 years ago.
I have a problem about some simple code in console. Precisely I created a public enum called Year which contains 4 seasons (obvious). I want the program to ask at the beginning what is the season of the year and then generate an answer to each option. The problem is I don't know how to convert my string input to each option of this enum. Maybe it will be more clear if i show you the code (it's short).
Console.WriteLine("What time of year is it?");
var input = Console.ReadLine();
//earlier it was just
//time = Year.Winter;
switch (time)
{
case Year.Autumn:
Console.WriteLine("You're gonna have to grab the leaves");
break;
case Year.Summer:
Console.WriteLine("Let's go to the beach");
break;
case Year.Winter:
Console.WriteLine("Better to warm up at home");
break;
case Year.Spring:
Console.WriteLine("Best time of the year!");
break;
default:
Console.WriteLine("I don't know this time of year");
break;
}
I want to make something like this but dunno what to put inside this switch statement because I can't just put there my string 'input'. Is it possible in the way I am thinking of it?
You can parse a try to parse a string into an Enum by using one of the Enum class.
In particular, you can use the typed method TryParse in this eay
var ignoreCase = true; // decide this
if (Enum.TryParse<MyEnum>("my string", ignoreCase, out var r))
// use r
else
Console.WriteLine("Please enter the correct value.");
You can use string contain() function before the switch statment like below i haven't tested if it works like this (nested) if not you have to use if and else if condition
time = input.Trim().Contains("winter") ? Year.Winter: (input.Trim().Contains("summer") ?Year.Summer :(input.Trim().Contains("autumn") ?Year.Autumn:i(nput.Trim().Contains("autumn") ?Year.Autumn: null)));
The other thing you can do is give user option like 1 Year.Autumn,2 Year.Summer,3 Year.Winter,4 Year.Spring and get a number on which you can use the switch statment
I'm trying to get a enum value from a string in a database, below is the enum I am trying to get the value from, the DB value is a string.
internal enum FieldType
{
Star,
Ghost,
Monster,
Trial,
None
}
Heres the DB part:
using (var reader = dbConnection.ExecuteReader())
{
var field = new Field(
reader.GetString("field_type"),
reader.GetString("data"),
reader.GetString("message")
);
}
Now, I had this method that did it for me, but it seems overkill to have a method do something that C# could already do, can anyone tell me if theres a way I can do this within the C# language without creating my own method?
public static FieldType GetType(string Type)
{
switch (Type.ToLower())
{
case "star":
return FieldType.Star;
case "ghost":
return FieldType.Ghost;
case "monster":
return FieldType.Monster;
case "trial":
return FieldType.Trial;
default:
case "none":
return FieldType.None;
}
}
In essence, I believe what you need is parsing from string to an enum. This would work if the value of the string is matching the enum value (in which it seems it is here).
Enum.TryParse(Type, out FieldType myFieldType);
Enum.TryParse(Type, ignoreCase, out FieldType myFieldType);
First method case-sensitive while the second allows you to specify case sensitivity.
How should I convert a string to an enum in C#?
Let's define a test string first:
String text = "Star";
Before .NET 4.0 (MSDN reference):
// Case Sensitive
FieldType ft = (FieldType)Enum.Parse(typeof(FieldType), text, false);
// Case Insensitive
FieldType ft = (FieldType)Enum.Parse(typeof(FieldType), text, true);
but with Enum.Parse you have to manage a potential exception being thrown if the parsing process fails:
FieldType ft;
try
{
ft = (FieldType)Enum.Parse(typeof(FieldType), text, true);
}
catch (Exception e)
{
ft = FieldType.None;
}
Since .NET 4.0 (MSDN reference):
FieldType ft;
// Case Sensitive
if (!Enum.TryParse(text, false, out ft))
ft = FieldType.None;
// Case Insensitive
if (!Enum.TryParse(text, true, out ft))
ft = FieldType.None;
I use Substring to decode a generated code for activating
but when a user enter wrong code like 1 or 123
c# stop and say "Index and length must refer to a location within the string." or ..
how to ignore it without check length ...
in php we can ignore warnings and error by using "#"
#myfunc(12);
but how in C# ?
The short answer is, you can't.
The correct answer is you shouldn't, and to check that the input is valid.
The horrible answer would look something like this:
public void SwallowExceptions(Action action)
{
try
{
action();
}
catch
{
}
}
public string DoSomething()
{
string data = "TerribleIdea";
string result = null;
SwallowExceptions(() => result = data.Substring(0, 10000));
return result;
}
I'm using Visual Studio 2008 and trying to convert this switch statement
switch (salesOrderPayment.PaymentCardKey.ToUpper()) {
case "MC":
ValidateCreditCard(salesOrderPayment,errorMessages);
break;
case "VISA":
ValidateCreditCard(salesOrderPayment, errorMessages);
break;
case "TELECHECK":
//ValidateTelecheck(salesOrderPayment, errorMessages);
ValidateAchCheck(salesOrderPayment, errorMessages);
break;
case "ACH":
ValidateAchCheck(salesOrderPayment, errorMessages);
break;
To use an enum that I have created
public enum PaymentType {
MC,
VISA,
AMEX,
TELECHECK,
CASH,
ACH }
I've tried this:
switch (Enum.Parse(typeof(PaymentType),salesOrderPayment.PaymentCardKey.ToUpper()))
but get red squiggly lines and when I hover over it says "A value of an integral type expected".
Try this:
switch ((PaymentType)Enum.Parse(typeof(PaymentType),salesOrderPayment.PaymentCardKey,true)))
Notice the cast to PaymentType type, also note that your switch cases has to be enum fields rather than strings.
I've used another overload of Enum.Parse which takes bool ignoreCase as parameter, make use of it so that you don't need ToUpper call.
As the Enum.Parse method returns with an Object (see here), you will need to cast the result of Enum.Parse to PaymentType.
Shamed by this simple question. For some reason, I want to put all asp.net URLs in an enum. But I got an error: identifer expected
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Admin.Code
{
public enum url
{
/_layouts/Admin/test1.aspx,
/_layouts/Admin/test2.aspx,
/_layouts/Admin/test3.aspx
}
class AdminUrlSettings
{
}
}
Thanks.
Here's something I've done many times to turn enumerated values into "friendly strings". You can also use it to create "string-valued" enums. It's in the same vein as Msonic's solution, but the attribute is built into the Framework.
public enum url
{
[Description(#"/_layouts/Admin/test1.aspx")] Test1,
[Description(#"/_layouts/Admin/test2.aspx")] Test2,
[Description(#"/_layouts/Admin/test2.aspx")] Test3
}
...
public static string GetDescription(this Enum enumValue)
{
object[] attr = enumValue.GetType().GetField(enumValue.ToString())
.GetCustomAttributes(typeof (DescriptionAttribute), false);
if (attr.Length > 0)
return ((DescriptionAttribute) attr[0]).Description;
return enumValue.ToString();
}
//usage
Response.Redirect(url.Test1.GetDescription());
These aren't valid enum identifiers. You'll need string enumerations. Here's an example
You will be able to do something like this:
public enum url
{
[StringValue("/_layouts/Admin/test1.aspx")]
Test1,
[StringValue("/_layouts/Admin/test2.aspx")]
Test2,
[StringValue("/_layouts/Admin/test3.aspx")]
Test3
}
Identifiers in C# can't contain / characters. They are limited to underscores, letters and numbers (and possibly a # prefix). To fix this you need to make the enum values valid C# identifiers
enum url {
test1,
test2,
test3
}
Later turning these into an actual valid url can be done with a switch statement over the value
public static string GetRelativeUrl(url u) {
switch (u) {
case url.test1:
return "/_layouts/Admin/test1.aspx";
case url.test2:
return "/_layouts/Admin/test2.aspx";
case url.test3:
return "/_layouts/Admin/test3.aspx";
default:
// Handle bad URL, possibly throw
throw new Exception();
}
}
Enums don't really work like that. Valid identifiers work the same way variable names do (ie. a combination of letters, numbers and underscores not beginning with a number). Why not just use a list:
List<string> urls = new List<string>{"/_layouts/Admin/test1.aspx", "/_layouts/Admin/test2.aspx", "/_layouts/Admin/test3.aspx"}
or use slightly different identifiers:
public enum url
{
layout_Admin_test1,
layout_Admin_test2,
layout_Admin_test3
}