I have a class MyClass which has
public enum Days{Mon, Tue, Wed}
and then a field
public Days dayOfWeek;
From another class in my solution I have a string (myString) value of either 0, 1 or 2. I want to set an instance of MyClass's (called myClassInstance) field dayOfWeek equal to myStringvalue such that 0 means Mon, 1 means Tue...
I have tried
myClassInstance.dayOfWeek = Convert.ToInt32(myString)
and
myClassInstance.dayOfWeek = (int) myString
but neither work. I'm sure this is straightforward. Why don't these techniques work?
Try
string s = "0";
Days day = (Days)Enum.Parse(typeof(Days), s);
or
string s = "0";
Days day;
if(!Enum.TryParse(s, out day)) {
// error handling
}
to gracefully handle the case where s can't be parsed to an instance of Days.
This works per the documentation for Enum.Parse which states
Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
Additionally, you can check if the instance of string actually represents a value defined by the enum via
string s = "3";
bool defined = Enum.IsDefined(typeof(Days), s);
// defined is false
Enum.Parse will blindly parse s in this case, even though it doesn't represent a value defined by the enum Days and the cast from the result of Enum.Parse to Days will not fail.
Moreover, there is a built-in enum that represents the days of the week. This enum is System.DayOfWeek. I would suggest using this.
Finally, if for some reason you can't use System.DayOfWeek, you should at a minimum rename your enum to Day instead of Days (remove the pluralization). Only enums that represent flags should be pluralized. Note that the variable day above represents a day, and it does not represent days. This is why you should rename the enum to Day. This is consistent with the naming conventions that most C# and .NET programmers use.
You just need to cast the int to the Days enum after converting it:
myClassInstance.dayOfWeek = (Days)Convert.ToInt32(myString);
You can also use Enum.TryParse (if you're in .NET 4) or Enum.Parse. Depending on how much your trust the incoming data, you may also want to call Enum.IsDefined to make sure that the integer is a valid value of Days (otherwise, in all of these cases, you'll have an instance of Days that doesn't correspond to any of your named values).
Days dayOfWeek;
if (!Enum.TryParse(myString, out dayOfWeek)) {
dayOfWeek = Days.Mon; // or some other default, or throw
}
myClassInstance.dayOfWeek = dayOfWeek;
Or
myClassInstance.dayOfWeek = (Days)Enum.Parse(typeof(Days), myString);
In addition, as others have mentioned, you may want to consider using the built-in DayOfWeek enum instead of your custom version, if it matches what you really want.
Also, as others have mentioned again, even if it doesn't, Day is a better name based on the .NET naming guidelines, since it isn't a Flags enum.
Try
myClassInstance.dayOfWeek = (Days)int.Parse(myString);
Do you know there is already an Enum that you can resuse called DayOfWeek (http://msdn.microsoft.com/en-us/library/system.dayofweek.aspx)
Try:
Days d = (Days)Enum.Parse(typeof(Days), myString);
A more complete example is here.
You need to cast the int to Days:
myClassInstance.dayOfWeek = (Days)Convert.ToInt32(myString);
What you want to do is cast the string to an int (or tryparse if you want to do it in a nice way)
Then use the Following code to set the enum value:
(Days)Enum.ToObject(typeof(Days), intValue);
This should work
myClassInstance.dayOfWeek = Enum.Parse(typeof(Days), myString);
Enump.Parse
Related
I need to get the current weekday number of the current week.
If I use DateTime.Now.DayOfWeek I get Monday, but it would be much easier to work with if I get 1 for Monday, 7 for Sunday etc. Thanks beforehand!
You can use this:
day1 = (int)DateTime.Now.DayOfWeek;
You can create an extension method to hide the implementation details.
Using an extension method and constraining T to IConvertible does the trick, but as of C# 7.3 Enum is an available constraint type:
public static class EnumExtensions
{
public static int ToInt<T>(this T source) where T : Enum
{
return (int) (IConvertible) source;
}
}
This then allows you to write:
DateTime.Now.DayOfWeek.ToInt();
Example:
Console.WriteLine(DayOfWeek.Monday.ToInt()); // outputs 1
Note: this solution assumes that int is used as the underlying Enum type.
DateTime.Now.DayOfWeek is an enum, and it is of (int) type, so the easiest way would be #faheem999 's answer.
But, if you are dealing with Enums with unknown type's, such as (byte , sbyte , short , ushort , int , uint , long or ulong), then either you need to know Enum type, or use another method:
DayOfWeek dayOfWeek = DateTime.Now.DayOfWeek;
object val = Convert.ChangeType(dayOfWeek, dayOfWeek.GetTypeCode());
For more information, look at this question Get int value from enum in C#
I'm trying to determine if a string value read-in from a file is found within an enum in my code.
The enum:
internal enum Difficulty { None, Easy, Medium, Hard }
At this point in my code header[i] = "EASY".
I want to compare this value to any of the values found in my Difficulty enum but am encountering issues.
The code:
Each time the following code is executed, the if statement returns false because "Easy" != "EASY".
Difficulty dif = Difficulty.None;
if (Difficulty.TryParse(header[i], out dif)) { // RETURNS FALSE
MyLog.Write("It's in the Enum!");
}
I've tried comparing the header[i] value to the Difficulty value in the TryParse statement, but it results in a compiler error.
Is there anything I can do besides changing all the Difficulty values to uppercase ones?
Use the version of TryParse that supports ignoring case: https://msdn.microsoft.com/en-us/library/dd991317(v=vs.110).aspx
Your code becomes:
Difficulty dif = Difficulty.None;
if (Enum.TryParse<Difficulty>(header[i], true, out dif))
{
MyLog.Write("It's in the Enum!");
}
The .ToString value for any Enum returns just the name your provide for it. So if you're gonna be doing this in a loop i suggest getting all the names to a local list and search in that which would result in better performance:
string[] enumNames = Enum.GetNames(typeof(Difficulty));
bool found = enumNames.Any(x => x.Equals(header[i], StringComparison.OrdinalIgnoreCase));
Yes there is!
Use the overload for Enum.TryParse that allows you to ignore the case:
if (Enum.TryParse("EASY", true, out dif))
{
Console.WriteLine("It's in the Enum!");
}
I've got a enum type defined in my C# code that corresponds to all possible values for the NetConnectionStatus field in Win32_NetworkAdapter WMI table, as documented here.
The documentation shows that the integers 0 through 12 each have a unique status name, but then all integers between 13 and 65,535 are lumped into one bucket called "Other." So here's my code:
[Serializable]
public enum NetConnectionStatus
{
Disconnected = 0,
Connecting = 1,
Connected = 2,
Disconnecting = 3,
HardwareNotPresent = 4,
HardwareDisabled = 5,
HardwareMalfunction = 6,
MediaDisconnected = 7,
Authenticating = 8,
AuthenticationSucceeded = 9,
AuthenticationFailed = 10,
InvalidAddress = 11,
CredentialsRequired = 12,
Other
}
This works fine for the values that are not Other. For instance, I can do this:
var result = (NetConnectionStatus) 2;
Assert.AreEqual(NetConnectionStatus.Connected, result);
But for anything in that higher numeric range, it doesn't work so great. I would like it if I could do this:
var result = (NetConnectionStatus) 20;
Assert.AreEqual(NetConnectionStatus.Other, result);
But right now that result variable gets assigned the literal value 20 instead of Other. Is there some out-of-the-box way of accomplishing this, something akin to Parse() but for integers instead of strings, or perhaps some special attribute I'm unaware of? I would prefer to not write my own wrapper method for this if there is already a good way to accomplish this.
If you have a string value, then the closest thing I can think of is to use Enum.TryParse:
NetConnectionStatus result;
if (Enum.TryParse(stringValue, out result) == false)
result = NetConnectionStatus.Other;
For an integer value that you're casting, you can use:
result = (NetConnectionStatus)integerValue;
if (Enum.GetValues(typeof(NetConnectionStatus)).Contains(result) == false)
result = NetConnectionStatus.Other;
Not really ideal, but in C# enums aren't much more than fancy names for integral values, so it's valid to stuff an integer value not in the defined values of the enums into a value of that enum type.
This solution will handle negative numbers, or cases where you have gaps in your enum values more elegantly than doing numerical comparisons.
it would be nice but no. How about
var result = (NetConnectionStatus) 20;
Assert.IsTrue(result >= (int)NetConnectionStatus.Other);
.NET does not such thing as a "any other" enumeration value bucket. Technically, enumeration (enum) is a pretty set of named constants of some underlying type (which is one of following: sbyte, short, int, long and their unsigned counterparts). You can cast an enum value to/from a corresponding type without any losses, as in this example:
enum TestEnum:int // Explicitly stating a type.
{
OnlyElement=0
}
class Program
{
static void Main(string[] args)
{
// Console.WriteLine implicitly calls ToString of the TestEnum.OnlyElement.
Console.WriteLine("OnlyElement == {0}", TestEnum.OnlyElement);
//TestEnum.OnlyElement equals to 0, as demonstrated by this casting:
Console.WriteLine("(int)OnlyElement == {0}", (int)TestEnum.OnlyElement);
//We can do it in reverse...
Console.WriteLine("(TestEnum)0 == ",(TestEnum)0);
// But what happens when we try to cast a value, which is not
// representable by any of enum's named constants,
// into value of enum in question? No exception is thrown
// whatsoever: enum variable simply holds that value, and,
// having no named constant to associate it with, simply returns
// that value when attempting to "ToString"ify it:
Console.WriteLine("(TestEnum)5 == {0}", (TestEnum)5); //prints "(TestEnum)5 == 5".
Console.ReadKey();
}
}
I'd like to repeat it again, enum in .NET is simply a value of the underlying type with some nice decorations like overriden ToString method and flags checking (look here or here if you want to know more about flags). You cannot have an integer with only 14 values like "0..12 and everything else", and so you cannot have such enum. In your example, NetConnectionStatus.Other simply receives single literal value (I assume it would most probably be '13', as the next available positive value of underlying type - however it actually depends on the compiler) as any other enumeration constant would do if not specified explicitly - and, obviously, it does not become a bucket.
However, there are options to achieve simple equation checks for integers/bytes/shorts/longs - and enums alike. Consider this extension method:
static bool IsOther(this NetConnectionStatus A)
{
return (A < (NetConnectionStatus)0) || (A > (NetConnectionStatus)12);
}
Now you can have a simple assertion like this:
var result = (NetConnectionStatus)10;
Trace.Assert(result.IsOther()); //No assertion is triggered; result is NetConnectionStatus.AuthenticationFailed
and
var result = (NetConnectionStatus)20;
Trace.Assert(result.IsOther()); //Assertion failed; result is undefined!
(Of course you can replace IsOther method with IsNotOther, overload it and pretty much anything else you could do with a method.)
Now there is one more thing. Enum class itself contains a method called IsDefined, which allows you to avoid checks for specific enum's value boundaries (<0, >12), therefore preventing unwanted bugs in case enum values would ever be added/removed, at the small performance cost of unboxing and checking each value in enum for a match (I'm not sure how this works under the hood though, I hope these checks are optimized). So your method would look like this:
static bool IsOther(NetConnectionStatus A)
{
return !Enum.IsDefined(typeof(NetConnectionStatus), A);
}
(However, concluding from enum's name, it seems like you want to make a network application/server, and for these performance might be of very great importance - but most probably I'm just being paranoid and this will not be your application's bottleneck. Stability is much more of concern, and, unless you experience real troubles with performance, it is considered to be much better practice to enable as much stability&safety&portability as possible. Enum.IsDefined is much more understandable, portable and stable than the explicit boundaries checking.)
Hope that helps!
Thanks everyone for the replies. As confirmed by all of you, there is indeed no way to do this out-of-the-box. For the benefit of others I thought I'd post the (custom) code I ended up writing. I wrote an extension method that utilizes a custom attribute on the enum value that I called [CatchAll].
public class CatchAll : Attribute { }
public static class EnumExtensions
{
public static T ToEnum<T, U>(this U value) where T : struct, IConvertible where U : struct, IComparable, IConvertible, IFormattable, IComparable<U>, IEquatable<U>
{
var result = (T)Enum.ToObject(typeof(T), value);
var values = Enum.GetValues(typeof(T)).Cast<T>().ToList();
if (!values.Contains(result))
{
foreach (var enumVal in from enumVal in values
let info = typeof(T).GetField(enumVal.ToString())
let attrs = info.GetCustomAttributes(typeof(CatchAll), false)
where attrs.Length == 1
select enumVal)
{
result = enumVal;
break;
}
}
return result;
}
}
So then I just have to apply that [CatchAll] attribute to the Other value in the enum definition. Then I can do things like this:
int value = 13;
var result = value.ToEnum<NetConnectionStatus, int>();
Assert.AreEqual(NetConnectionStatus.Other, result);
And this:
ushort value = 20;
result = value.ToEnum<NetConnectionStatus, ushort>();
Assert.AreEqual(NetConnectionStatus.Other, result);
What is main use of Enumeration in c#?
Edited:-
suppose I want to compare the string variable with the any enumeration item then how i can do this in c# ?
The definition in MSDN is a good place to start.
An enumeration type (also named an
enumeration or an enum) provides an
efficient way to define a set of named
integral constants that may be
assigned to a variable.
The main benefit of this is that constants can be referred to in a consistent, expressive and type safe way.
Take for example this very simple Employee class with a constructor:
You could do it like this:
public class Employee
{
private string _sex;
public Employee(string sex)
{
_sex = sex;
}
}
But now you are relying upon users to enter just the right value for that string.
Using enums, you can instead have:
public enum Sex
{
Male = 10,
Female = 20
}
public class Employee
{
private Sex _sex;
public Employee(Sex sex)
{
_sex = sex;
}
}
This suddenly allows consumers of the Employee class to use it much more easily:
Employee employee = new Employee("Male");
Becomes:
Employee employee = new Employee(Sex.Male);
Often you find you have something - data, a classification, whatever - which is best expressed as one of several discrete states which can be represented with integers. The classic example is months of the year. We would like the months of the year to be representable as both strings ("August 19, 2010") and as numbers ("8/19/2010"). Enum provides a concise way to assign names to a bunch of integers, so we can use simple loops through integers to move through months.
Enums are strongly typed constants. Enumerations are special sets of named values which all maps to a set of numbers, usually integers. They come in handy when you wish to be able to choose between a set of constant values, and with each possible value relating to a number, they can be used in a wide range of situations. As you will see in our example, enumerations are defined above classes, inside our namespace. This means we can use enumerations from all classes within the same namespace.
using System;
namespace ConsoleApplication1
{
public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
class Program
{
static void Main(string[] args)
{
Days day = Days.Monday;
Console.WriteLine((int)day);
Console.ReadLine();
}
}
}
Enumeration (Enum) is a variable type. We can find this variable type in C, C# and many other languages.
Basic Idea for Enum is that if we have a group of variable of integer type (by default) then instead of using too much int values just use a Enum. It is efficient way. Let suppose you want to write rainbow colours then you may write like this:
const int Red = 1;
const int Orange = 2;
const int Yellow = 3;
const int Green = 4;
const int Blue = 5;
const int Indigo = 6;
const int Violet = 7;
here you can see that too many int declarations. If you or your program by mistake change the value of any integer varialbe i.e. Violet = 115 instead of 7 then it will very hard to debug.
So, here comes Enum. You can define Enum for any group of variables type integers. For Enum you may write your code like this:
enum rainBowColors
{
red=1,
orange=2,
yellow=3,
green,
blue=8,
indigo=8,
violet=16)
};
rainBowColors is a type and only other variables of the same type can be assigned to this. In C#/C++ you need to type casting while in C you do not to type cast.
Now, if you want to declare a variable of type rainBowColors then in C
enum rainBowColors variableOne = red;
And in C# / C++ you can do this as:
rainBowColors variableOne = red;
There are two meanings of enumeration in C#.
An enumeration (noun) is a set of named values. Example:
public enum Result {
True,
False,
FileNotFound
}
Enumeration (noun form of the verb enumerate) is when you step through the items in a collection.
The IEnumerable<T> interface is used by classes that provide the ability to be enumerated. An array is a simple example of such a class. Another example is how LINQ uses it to return results as enumerable collections.
Edit:
If you want to compare a string to an enum value, you either have to parse the string to the enum type:
if ((Result)Enum.Parse(typeof(Result), theString) == Result.True) ...
or convert the enum value to a string:
if (theString == Result.True.ToString()) ...
(Be careful how you compare the values, depending on whether you want a case sensetive match or not.)
If you want to enumerate a collection and look for a string, you can use the foreach command:
foreach (string s in theCollection) {
if (s == theString) {
// found
}
}
Another advantage of using Enum is that in case of any of the integer value needs to be changed, we need to change only Enum definition and we can avoid changing code all over the place.
An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable.
http://msdn.microsoft.com/en-us/library/cc138362.aspx
Enumeration (ENUM)
An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.
Enums type can be integer (float, int, byte, double etc.). But if you used beside int it has to be cast.
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
enum Months : byte { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };
Lets Take an Example we are taking normal constant in a class like
int a=10;
by mistakely we assign new value to that variable in that same class like
a=20;
then we will get wrong data when we want access them.
enum provide secure way of accessing constant.
Also if we have many feild constant in a class we had to memorize them if we want to use them in a class.
but enum contains group of related name constant, if we want to access the constant then only we had to memorize enum name.
Enumerations in my experience have worked in very specific cases and should be used when you absolutely need to maintain this in your application. Problems come into play with Enums when you are working with multiple developers and some new developer comes on to a project and can adds a enum to the application no errors everything builds but then you have another full stack developer that maintains this same list in a lookup table in a different order. Kaboom!!!!
Burned way to many times with that one even if not intentional. Rule of thumb don't maintain a list of enums in a app over 5 or 6 items. If higher you might as well store them in a lookup table in the DB of your choice.
I am writing a Movie class that will have a Year property. Should it be just an int, or should I use a DateTime object?
Just wondering the best option. Maybe I am missing something.
I would probably use an int for simplicity, and make sure that in the setter you verify that the year value makes sense.
Alternatively, you can create a type to just represents years - this would make sure you don't misuse the year as a regular integral value. This gets complicated though, especially if you want to start overloading operators to support year addition and subtraction. Unless you really need this extra level of type safety, I would stick with an int.
If it's only going to be a year value, then int will be simpler. You could also consider just saving the release date as a DateTime, and get the year from that (instead of having a year attribute).
If it's only ever going to be the year then an int (or custom type) would do.
If you want to store the month as well then I'd use a DateTime.
The Agile mantra - YAGNI (You Ain't Gonna Need It) - would suggest an int until you want more information and then refactor into a DateTime then.
use datetime object you can get the year from it like .year well....
Well, DateTime has the unfortunate side-effect of specifying both a data and a time and not only some subsets. Ideally you would probably want some "time" object with varying levels of accuracy, as needed. But for this I'd suggest using an int since you are modeling exactly a year, not a complete date.
I would create a custom type, (a struct) to hold this value.
public struct FilmYear
{
private int yr;
private bool isDef;
public bool HasValue { return isDef; }
public bool IsNull { return !HasValue; }
private FilmYear(int year) { yr = year; isDef = true; }
public static FilmYear ThisYear = new FilmYear(DateTime.Today.Year);
public static FilmYear LastYear = new FilmYear(DateTime.Today.Year - 1);
public static FilmYear NextYear = new FilmYear(DateTime.Today.Year + 1);
public static FilmYear Parse(DateTime anyDateInYear)
{ return new FilmYear(anyDateInYear.Year); }
public static FilmYear Parse(int year)
{ return new FilmYear(year); }
public static FilmYear Parse(string year)
{ return new FilmYear(Int32.parse(year)); }
public overide string ToString()
{ return yr.ToString(); }
//etc... you can add:
// - operator overloads to add subtract years to the value,
// - conversion operator overloads to implicitly/(or explicitly)
// convert datetimes to FilmYears, as appropriate
// - overload equality and comparison operators ...
}
Usage
FilmYear avatarYear = FilmYear.ThisYear;
FilmYear casablancaYear = FilmYear.Parse(1943);
If this is for casual users, an int (or class based on int) is correct.
If you are doing a 'real' filmography, you'll need both an int and a string: the int for sorting and searching, with the string containing the "truth" of cases where the data is incomplete or tentative ("1958?").
This is also why you shouldn't use a Date or DateTime: there's no way to distinguish between "1/1/1958" and "sometime in 1958".
I think to properly answer that question, you need to supply a little more context. For what kind of application? Is this information going to be stored in a database? What kinds of queries do you expect users to perform against the data? Things like that.
If you're only looking to keep track of the Year, then keep it a int. If you're tracking the release date/production date, then use DateTime
For simplicity using an int is the most direct option; if there are any special methods for the data then creating a Year type and encapsulating all behaviors would be a clean and simple solution--if you go that route you can store the value as either an int or DateTime and offer .ToInt(), .ToDateTime(), methods and others to handle all use-cases.