C# user input referencing enum - c#

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;

Related

How can I pass enum variable name as parameter in c#

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!

How to pass a DaysOfTheWeek enum value dynamically through code

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
}

DateTime go to first occurrence of hour/minute/second

Given this datetime of January 1 2015 at 23:00 hours:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
And given the int 6, which is the desired hour, how do I return the first following datetime where the hour is 6? In this case, someDate and 6 would return a new DateTime of January 2 2015 at 06:00 hours.
I would simply add the hours to the original date and add another day if the result is before the original time:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
var result = someDate.Date.AddHours(6); // note the "Date" part
if (result < someDate) result = result.AddDays(1);
You just have to add one day to the date and six hours to the result:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
var result = someDate.Date.AddDays(1).AddHours(6);
Note the use of Date property - it will give you the start od the day and from there it's easy to navigate forward.
Try this:
while(someDate.Hour != 6){
someDate = someDate.AddHours(1);
}
Assuming you meant 24h clock, you can try this:
public DateTime GetDate(DateTime someDate,int hour)
{
return someDate.Hour>=hour? someDate.Date.AddDays(1).AddHours(6):someDate.Date.AddHours(6);
}
Something like this should do it:
public DateTime FollowingHour(DateTime start, int hour)
{
DateTime atHour = start.Date.AddHours(6);
if(atHour < start)
{
atHour += TimeSpan.FromDays(1);
}
return atHour;
}

How can I define an enumeration where multiple values map to a single label?

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
}

How to get the same time and Day next month using DateTime in c#

I have a c# DateTime object and I need to increment it by one month.
example:
input output
-------------------------------
Jan 12, 2005 Feb 12, 2005
Feb 28, 2009 Mar 28, 2009
Dec 31, 2009 Jan 31, 2010
Jan 29, 2000 Feb 29, 2000
Jan 29, 2100 Error: no Feb 29, 2100
What is the best way to do this.
My first thought (aside from some built in code) was to construct a new DateTime from pieces and handle the roll to the year myself
Here's a complete program showing the examples given in the question. You'd probably want to use an exception in OneMonthAfter if it really shouldn't be called that way.
using System;
using System.Net;
public class Test
{
static void Main(string[] args)
{
Check(new DateTime(2005, 1, 12));
Check(new DateTime(2009, 2, 28));
Check(new DateTime(2009, 12, 31));
Check(new DateTime(2000, 1, 29));
Check(new DateTime(2100, 1, 29));
}
static void Check(DateTime date)
{
DateTime? next = OneMonthAfter(date);
Console.WriteLine("{0} {1}", date,
next == null ? (object) "Error" : next);
}
static DateTime? OneMonthAfter(DateTime date)
{
DateTime ret = date.AddMonths(1);
if (ret.Day != date.Day)
{
// Or throw an exception
return null;
}
return ret;
}
}
using System;
public static class Test
{
public static void Main()
{
string[] dates = { "Jan 12, 2005", "Feb 28, 2009", "Dec 31, 2009", "Jan 29, 2000", "Jan 29, 2100" };
foreach (string date in dates)
{
DateTime t1 = DateTime.Parse(date);
DateTime t2 = t1.AddMonths(1);
if (t1.Day != t2.Day)
Console.WriteLine("Error: no " + t2.ToString("MMM") + " " + t1.Day + ", " + t2.Year);
else
Console.WriteLine(t2.ToString("MMM dd, yyyy"));
}
Console.ReadLine();
}
}
This works for me:
DateTime d = DateTime.Now;
d.AddMonths(1);

Categories