my enum :
public enum UNH
{
Message_Reference_Identifier = 0,
Message_Type = 1,
Message_version_number = 2,
Message_release_number = 3,
Controlling_agency = 4,
Association_assigned_code = 5
}
my code line :
int tagcount = Enum.GetNames(typeof(UNH)).Length;
My question is how can I pass UNH as a parameter to typeof(), where UNH will be stored in a string variable.
Hello all, I have multiple enums let's say ABC, DEF, GHI. I would be receiving a string as input parameter, the string would be something like this "ABC+anythinghere", "DEF+anythinghere" and so on. So from here depending on first 3 characters of string parameter i.e. ABC, DEF.... I need to call enum properties which are of same name.
Example if first 3 chars are ABC then there would be n enum values for it similarly if first 3 chars are DEF then there would be m enum values for it.
This first 3 chars would be retrieved from the input string parameter in the form of string let's say testname, when passing the string name into typeof() like typeof(testname) it would obviously consider the variable as string which is not required instead I need a way where the value of testname i.e ABC, DEF.... would be passed into typeof()
Maybe I misunderstood the question, but this may help:
Enum.GetName:
public class Example
{
public enum Days
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7
}
public static void Main()
{
int value = 5;
string day = Enum.GetName(typeof(Days), value);
Console.WriteLine(day);
}
}
// Output: Friday
Using casting:
public class Example
{
public enum Days
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7
}
public static void Main()
{
int value = 5;
var day = (Days)value;
Console.WriteLine(day);
}
}
/*
Output: Friday
*/
Hope this help you to solve a problem you got!
Related
Here is my assignment: In your program, ask the user to enter the name of a month. Your program will output the corresponding value for that month.
Example of desired output:
Enter the name of a month: April
April is month 4
Here is my current code. I'm not a programmer, and I've somehow kind of reversed the point of the exercise:
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Enter the name of a month: ");
String month1 = System.Console.ReadLine();
Months month = (Months)Convert.ToInt32(month1);
System.Console.WriteLine(month);
}
}
enum Months
{
January = 1,
February = 2,
March = 3,
April = 4,
May = 5,
June = 6,
July = 7,
August = 8,
September = 9,
October = 10,
November = 11,
December = 12,
}
The output of mine requires the number of the month, then gives the actual month.
Thank you.
Have a look at Enum.Parse Method.
The exmple in the Remarks section even shows how to handle values that are not defined:
string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
foreach (string colorString in colorStrings)
{
try {
Colors colorValue = (Colors) Enum.Parse(typeof(Colors), colorString);
if (Enum.IsDefined(typeof(Colors), colorValue)
...
Perhaps consider avoiding enums entirely:
int month = DateTime.TryParse($"1 {input} 2022", out DateTime value) ? value.Month : -1;
I have the below enum value in task scheduler class, while I am creating a task I need to add days of the week depending on the checkbox selection. If the Monday checkbox is selected, I need to pass only Monday (or sometimes multiple days if other checkboxes are also selected).
In that below code how can I pass the multiple days dynamically?
public enum DaysOfTheWeek: short
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
AllDays = 127
}
DaysOfWeek = DaysOfTheWeek.Monday | DaysOfTheWeek.Sunday;
You can loop through your select list like this and create your enum value:
var days = new[] {1, 4, 32};
var daysOfTheWeek = DaysOfTheWeek.None;
foreach (var day in days)
{
daysOfTheWeek = daysOfTheWeek | (DaysOfTheWeek) day;
}
[Flags]
public enum DaysOfTheWeek
{
None = 0,
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
AllDays = 128
}
Decorate your enum with the Flags attribute:
[Flags]
public enum DaysOfTheWeek : short
Declare a DaysOfTheWeek variable and initialise it to zero:
DaysOfTheWeek days = 0;
Add flags to the enum value for each day which is ticked. Replace bool sunday = true, wednesday = true; here with your code which examines the checkboxes:
bool sunday = true, wednesday = true; // this is just proof of concept
if (sunday)
days |= DaysOfTheWeek.Sunday;
if (wednesday)
days |= DaysOfTheWeek.Wednesday;
days output:
Sunday, Wednesday
Your question doesn't mention loop, but your reply to my comment does. Do you mean something like:
DaysOfWeek = DaysOfTheWeek.Monday | DaysOfTheWeek.Sunday;
foreach (int day in Enum.GetValues(typeof(DaysOfTheWeek)))
{
if ( day & DaysOfWeek ) {
/* do something for this day */
}
}
As Shahriar Gholami suggested, here the complete code:
class Program
{
static void Main(string[] args)
{
var daysOfWeek = GetDaysOfTheWeek(new List<DaysOfTheWeek> {DaysOfTheWeek.Monday, DaysOfTheWeek.Sunday});
Console.WriteLine(daysOfWeek); //3
}
public static DaysOfTheWeek GetDaysOfTheWeek(List<DaysOfTheWeek> selectedDays)
{
var daysOfTheWeek = DaysOfTheWeek.None;
foreach (var day in selectedDays)
{
daysOfTheWeek = daysOfTheWeek | day;
}
return daysOfTheWeek;
}
}
[Flags]
public enum DaysOfTheWeek : short
{
None = 0,
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
AllDays = 127
}
I have two enums and I want to determine from user input(string), in which array is the enum with the same name from user input
public enum LengthUnit
{
mm = -3,
cm = -2,
dm = -1,
m = 0,
km = 3
}
public enum NumericUnit
{
b = 2,
o = 8,
d = 10,
h = 16
}
string input = "cm";
Sounds like you want Enum.TryParse which will let you pass a string and the enum type as parameters and an out parameter as the result if the TryParse succeeds.
Suppose, for the sake of this example, that I am trying to parse a file which specifies that two arbitrary bytes in the record represent the day of the week, thusly:
DayOfWeek:
- 0 = Monday
- 1 = Tuesday
- 2 = Wednesday
- 3 = Thursday
- 4 = Friday
- 5 = Saturday
- 6 = Sunday
- 7-15 = Reserved for Future Use
I can define an enumeration to map to this field, thusly:
public enum DaysOfWeek
{
Monday = 0,
Tuesday = 1,
Wednesday = 2,
Thursday = 3,
Friday = 4,
Saturday = 5,
Sunday = 6
ReservedForFutureUse
}
But how can I define valid values for ReservedForFutureUse? Ideally, I'd like to do something like:
public enum DaysOfWeek
{
Monday = 0,
Tuesday = 1,
Wednesday = 2,
Thursday = 3,
Friday = 4,
Saturday = 5,
Sunday = 6
ReservedForFutureUse = {7,8,9,10,11,12,13,14,15}
}
This problem is only exacerbated with more complicated fields; suppose, for example, that both 7 and 8, in this case, map to the same error case or something. How can one capture this requirement in a C# enumeration?
One funny quirk with enums is that a variable defined as a certain enum type can hold values that are not defined by any member of that enum:
public enum DaysOfWeek
{
Monday = 0,
Tuesday = 1,
Wednesday = 2,
Thursday = 3,
Friday = 4,
Saturday = 5,
Sunday = 6
}
// in other code
DaysOfWeek someDay = (DaysOfWeek)42; // this is perfectly legal
This means that you don't really need to define all possible values that can appear, but can rather just specify those that mean something to your code. Then you can use some "catch-all" if- or switch-block to handle undefined values:
switch (someDay)
{
case DaysOfWeek.Monday:
{
// do monday stuff
break;
}
case DaysOfWeek.Tuesday:
{
// do tuesday stuff
break;
}
// [...] handle the other weekdays [...]
default:
{
// handle undefined values here
break;
}
}
Although a given underlying value may be mapped to multiple enum values, an enum value can have exactly one underlying value.
You could just do this
public enum DaysOfWeek
{
Monday = 0,
Tuesday = 1,
Wednesday = 2,
Thursday = 3,
Friday = 4,
Saturday = 5,
Sunday = 6
Reserved1 = 7
...
Reserved8 = 15
}
I did a test like below ↓
1) Create a customer enum (copy from the dayofweek)
[Serializable]
public enum Tester
{
// 概要:
// Indicates Sunday.
Sunday = 0,
//
// 概要:
// Indicates Monday.
Monday = 1,
//
// 概要:
// Indicates Tuesday.
Tuesday = 2,
//
// 概要:
// Indicates Wednesday.
Wednesday = 3,
//
// 概要:
// Indicates Thursday.
Thursday = 4,
//
// 概要:
// Indicates Friday.
Friday = 5,
//
// 概要:
// Indicates Saturday.
Saturday = 6,
}
2) Create two test method ...
static void TestEnumToString()
{
var t = Tester.Sunday;
Enumerable.Range(0, 1000000).ToList().ForEach(i => t.ToString());
}
static void DayOfWeekEnumToString()
{
var t = DayOfWeek.Sunday;
Enumerable.Range(0, 1000000).ToList().ForEach(i => t.ToString());
}
3) Main method
static void Main()
{
Stopwatch sw = new Stopwatch();
sw.Start();
TestEnumToString();
sw.Stop();
Console.WriteLine("Tester:" + sw.ElapsedMilliseconds);
sw = new Stopwatch();
sw.Start();
DayOfWeekEnumToString();
sw.Stop();
Console.WriteLine("DayOfWeek:" + sw.ElapsedMilliseconds);
Console.ReadKey();
}
4) The result :
Tester : 3164ms
DayOfWeek : 7032ms
I really don't know why the system type enum is slower than the customer enum type....
Could anybody tell me why ?
Thank you...
UPDATE EDIT:
Add the [ComVisible(true)] to the enum .
[ComVisible(true)]
[Serializable]
public enum Tester
{
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
}
The Result :
Tester : 5018ms
DayOfWeek : 7032ms
The system enum type still slower than the customer enum type...
Enum can be decorate with [ComVisible(true)] or [Flags] and each time it changes the result of your test .
[Serializable]
//[Flags]
[ComVisible(true)]
public enum Tester
{
// 概要:
// Indicates Sunday.
Sunday = 0,
You should add the [ComVisible(true)] attribute if you want to compare apples to apples.