I have a set of codes that are particular to the application (one to one mapping of the code to its name), and I've been using enums in C# to represent them. I'm not sure now if that is even necessary. The values never change, and they are always going to be associated with those labels:
Workflow_Status_Complete = 1
Workflow_Status_Stalled = 2
Workflow_Status_Progress = 3
Workflow_Status_Complete = 4
Workflow_Status_Fail = 5
Should I use an enum or a class with static members?
Static members of type int seems to be inferior to an enum to me. You lose the typesafety of an enum. And when debugging you don't see the symbolic name but just a number.
On the other hand if an entry consists of more than just a name/integervalue pair a class can be a good idea. But then the fields should be of that class and not int. Something like:
class MyFakeEnum
{
public static readonly MyFakeEnum Value1=new MyFakeEnum(...);
}
Use an enum. Even though your codes never change, it will be difficult to know what the value represents just by inspection. One of the many strengths of using enums.
enum RealEnum : uint
{
SomeValue = 0xDEADBEEF,
}
static class FakeEnum
{
public const uint SomeValue = 0xDEADBEEF;
}
var x = RealEnum.SomeValue;
var y = FakeEnum.SomeValue;
// what's the value?
var xstr = x.ToString(); // SomeValue
var ystr = y.ToString(); // 3735928559
Not even the debugger will help you much here, especially if there are many different values.
Check out the State Pattern as this is a better design. With the idea you are using you'll end up with a large switch/if-else statement which can be very difficult to keep up.
I would lean towards enums as they provide more information and they make your codes "easier to use correctly and difficult to use incorrectly". (I think the quote is from The Pragmatic Programmer.
Related
For example, here is a simple enum:
enum Something {
One = 1,
Two = 2,
Three = 3
}
But I would like to create the opposite of this code, like
SomeType Something {
1 = One,
2 = Two,
3 = Threee
}
Maybe I could introduce constants, like
static class Something {
public const 1 = "One";
// ...
}
but I get compiler errors (CS1031, CS1001, CS0145 and CS1003), because c# can't handle this.
I can do the same with enums to prevent these unnecessary errors, but here I also get CS1001, because c# does not undertand that the numbers are the identifiers.
I can also use strings, but this makes it even more complicated, because c# expects another identifier for them (but doesn't accept one (CS0029))
So, is there anything in c# that can be used to assign some string-like values to numbers as constants or like enums?
You can not have numeric value as your variable name, So to solve this issue you can create a Dictionary of key integer and value as string like this Dictionary<int, string> and use it accordingly.
If that's how to use the enum name, you can use Enum.TryParse<someEnumTyme>(someString, out _someEnumVar).
But the Dictionary solution of is more elegant in my opinion.
At runtime, for many operations, using an enum variable is the same as using the underlying type.
enum Something {
One = 1,
Two = 2,
Three = 3
}
Something foo = Something.One; // assign 1 to foo
You can use the definition of an enum to create a mapping between values and names;
var lookup = ((Something[])Enum.GetValues(typeof(Something)))
.ToDictionary(e => e.ToString(), e => (int)e);
Is it possible in C# to turn a bool into a byte or int (or any integral type, really) without branching?
In other words, this is not good enough:
var myInt = myBool ? 1 : 0;
We might say we want to reinterpret a bool as the underlying byte, preferably in as few instructions as possible. The purpose is to avoid branch prediction fails as seen here.
unsafe
{
byte myByte = *(byte*)&myBool;
}
Another option is System.Runtime.CompilerServices.Unsafe, which requires a NuGet package on non-Core platforms:
byte myByte = Unsafe.As<bool, byte>(ref myBool);
The CLI specification only defines false as 0 and true as anything except 0 , so technically speaking this might not work as expected on all platforms. However, as far as I know the C# compiler also makes the assumption that there are only two values for bool, so in practice I would expect it to work outside of mostly academic cases.
The usual C# equivalent to "reinterpret cast" is to define a struct with fields of the types you want to reinterpret. That approach works fine in most cases. In your case, that would look like this:
[StructLayout(LayoutKind.Explicit)]
struct BoolByte
{
[FieldOffset(0)]
public bool Bool;
[FieldOffset(0)]
public byte Byte;
}
Then you can do something like this:
BoolByte bb = new BoolByte();
bb.Bool = true;
int myInt = bb.Byte;
Note that you only have to initialize the variable once, then you can set Bool and retrieve Byte as often as you like. This should perform as well or better than any approach involving unsafe code, calling methods, etc., especially with respect to addressing any branch-prediction issues.
It's important to point out that if you can read a bool as a byte, then of course anyone can write a bool as a byte, and the actual int value of the bool when it's true may or may not be 1. It technically could be any non-zero value.
All that said, this will make the code a lot harder to maintain. Both because of the lack of guarantees of what a true value actually looks like, and just because of the added complexity. It would be extremely rare to run into a real-world scenario that suffers from the missed branch-prediction issue you're asking about. Even if you had a legitimate real-world example, it's arguable that it would be better solved some other way. The exact alternative would depend on the specific real-world example, but one example might be to keep the data organized in a way that allows for batch processing on a given condition instead of testing for each element.
I strongly advise against doing something like this, until you have a demonstrated, reproducible real-world problem, and have exhausted other more idiomatic and maintainable options.
Here is a solution that takes more lines (and presumably more instructions) than I would like, but that actually solves the problem directly, i.e. by reinterpreting.
Since .NET Core 2.1, we have some reinterpret methods available in MemoryMarshal. We can treat our bool as a ReadOnlySpan<bool>, which in turn we can treat as a ReadOnlySpan<byte>. From there, it is trivial to read the single byte value.
var myBool = true;
var myBoolSpan = MemoryMarshal.CreateReadOnlySpan(ref myBool, length: 1);
var myByteSpan = MemoryMarshal.AsBytes(myBoolSpan);
var myByte = myByteSpan[0]; // =1
maybe this would work? (source of the idea)
using System;
using System.Reflection.Emit;
namespace ConsoleApp10
{
class Program
{
static Func<bool, int> BoolToInt;
static Func<bool, byte> BoolToByte;
static void Main(string[] args)
{
InitIL();
Console.WriteLine(BoolToInt(true));
Console.WriteLine(BoolToInt(false));
Console.WriteLine(BoolToByte(true));
Console.WriteLine(BoolToByte(false));
Console.ReadLine();
}
static void InitIL()
{
var methodBoolToInt = new DynamicMethod("BoolToInt", typeof(int), new Type[] { typeof(bool) });
var ilBoolToInt = methodBoolToInt.GetILGenerator();
ilBoolToInt.Emit(OpCodes.Ldarg_0);
ilBoolToInt.Emit(OpCodes.Ldc_I4_0); //these 2 lines
ilBoolToInt.Emit(OpCodes.Cgt_Un); //might not be needed
ilBoolToInt.Emit(OpCodes.Ret);
BoolToInt = (Func<bool, int>)methodBoolToInt.CreateDelegate(typeof(Func<bool, int>));
var methodBoolToByte = new DynamicMethod("BoolToByte", typeof(byte), new Type[] { typeof(bool) });
var ilBoolToByte = methodBoolToByte.GetILGenerator();
ilBoolToByte.Emit(OpCodes.Ldarg_0);
ilBoolToByte.Emit(OpCodes.Ldc_I4_0); //these 2 lines
ilBoolToByte.Emit(OpCodes.Cgt_Un); //might not be needed
ilBoolToByte.Emit(OpCodes.Ret);
BoolToByte = (Func<bool, byte>)methodBoolToByte.CreateDelegate(typeof(Func<bool, byte>));
}
}
}
based on microsoft documentation of each emit.
load the parameter in memory (the boolean)
load in memory a value of int = 0
compare if any the parameter is greater than the value (branching here maybe?)
return 1 if true else 0
line 2 and 3 can be removed but the return value could be something else than 0 / 1
like i said in the beginning this code is taken from another response, this seem to be working yes but it seem slow while being benchmarking, lookup .net DynamicMethod slow to find way to make it "faster"
you could maybe use the .GetHashCode of the boolean?
true will return int of 1 and false 0
you can then var myByte = (byte)bool.GetHashCode();
Recently I saw a person heavily using var and default keywords for declaration of variables (and for every declaration), something like this:
var employee = default(Employee); //Employee is a class
var errorInfo = default(ErrorInfo); //ErrorInfo is struct; Blank is default value
var salary = default(Double);
var isManager = default(Boolean?);
instead of using:
Employee employee = null; //Employee is a class
ErrorInfo errorInfo = Blank; //ErrorInfo is struct; Blank is default value
Double salary = 0.0;
Boolean? isManager = null;
or, instead of using even:
Employee employee; //Employee is a class
ErrorInfo errorInfo; //ErrorInfo is struct; Blank is default value
Double salary;
Boolean? isManager;
Now using var and default for declaration for every variable is something i am not accustomed to.
Want to know:
- If this is a recommended practice?
- Your views and preference?
PS:
- Have gone through Use of var keyword in C#, Use of "var" type in variable declaration and https://stackoverflow.com/questions/633474/c-do-you-use-var, however, think that this question although related is slightly different as it is solely around declaration/initialization and not around assignment.
- I understand the difference between snipped 2 and snippet 3. However, question is more around snippet 1.
- If you strongly feel that this question belongs to programmers stackexchange feel free to move.
I'm not going to say anything about "var" there have been comments and discussions about this in the past (sufficiently so ;-)
Concerning "default()" I would not use this to initialize a known type, but rather only in generics. There it helps to transparently handle value types or reference types by allowing you to provide a default (return) value or can be used in comparisons.
Well, the default keyword isn't the most used keyword I think, and in my opinion it serves its purpose best in terms of Generics, like so:
public class Foo<T>{
private T _instance;
public Foo<T>(){
_instance = default(T);
}
}
in order to get a new default instance of T.
There are really no reasons to use it like scenario 1 in your post.
Using var however is a different question, and many view this as a matter of readability. I default to var when I write code simply because I find it easier to read:
var me = new Person();
It seems a bit redundant in terms of readability to do
Person me = new Person();
Another case I recommend var is if something changes. Consider the following example:
public decimal Calculate(decimal one, decimal two){
return one + two;
}
And somewhere else in your code:
decimal d = Calculate(1M, 2M);
If you for some reason change the return type of Calculate to, say, double you need to change all the places where you strongly defined the variable.
If you instead do
var d = Calculate(1M, 2M)
you don't have to worry about this. The Double/Decimal example is a bit simple, but in terms of refactoring and interfacing out classes, I've found this very useful.
I think this is bad practice which will prevent the compiler (and 3rd party tools) from catching bugs related to failure to initialize a variable. Generally I try to keep declaration and assignment as close to each other as possible. Assigning values that aren't intended to be used to variables can potentially introduce subtle bugs that are difficult to catch. Normally I'd either:
SomeType variable1; //want to store something that will be out of scope later
using(blah)
{
//...
variable1=blah;
}
//use variable1 here
or assign required value immediately:
SomeType variable2 = new SomeType();
//use variable2 immediately
or (for me, more frequently nowdays)
var variable2 = new SomeType();
assigning null/placeholder values is mainly pointless.
I use var for assignment. However I always declare instances using the class. I generally also instantiate them at the time to avoid unexpected NullReferenceExceptions
The code is ok.
Just make sure that you don't copy this technique to initialize enums where 0 is not default value or flagged enumerations.
[Flags]
public enum MyFlags
{
Test = 1,
Test2 = 2
}
MyFlags flags = default(MyFlags);
Console.WriteLine(flags); // oops
I like to use enum as value holders whereever possible and I like it. It is easy to use i.e. just put a dot and see values. It is a good replacement of hard code some time.
But still it has some limitations. We cannot put special characters in values and some other.
Actually I am trying to make code reusable. Please guide me. Is there some technique or way that I can use some data structure like enum that is flexible but have no limitations.
You could use constants; they are immutable and can have any value.
See also: http://msdn.microsoft.com/en-us/library/ms173119.aspx
If I cannot use an enum for a set of predefined values, I use a class of static constants. They look much the same in use, but the values can be anything from a decimal to a string to a struct or class. I've done this for predefined cell color schemes in GridViews, much like the built-in Color class has predefined constant values. Mathematical and scientific constants such as e and Pi (if you wanted different values than are provided by the Math class), or the acceleration of gravity (9.8m/s2), or the speed of light (299,792,458m/s), can also be specified in this way.
If you think you can't use Enums because you need to store predefined string values, try this handy trick using the System.ComponentModel Description attribute:
public Enum MyStrings
{
[Description("This is string one")] StringOne,
[Description("This is a different string")] StringTwo,
...
}
To get the strings out, you simply examine the Description attribute, the code for which is a little messy but can be easily hidden behind an extension method:
public static string GetDescription(this Enum enumValue)
{
object[] attr = enumValue.GetType().GetField(enumValue.ToString())
.GetCustomAttributes(typeof (DescriptionAttribute), false);
return (attr.Length > 0)
? ((DescriptionAttribute) attr[0]).Description
: String.Empty;
}
Usage:
var stringOne = MyStrings.StringOne.GetDescription(); //"This is string one"
In this case, you can also consider using a Resource file. The value of the string can be changed from outside the scope of the program, without a recompile.
Not sure what exactly you need (re: "special characters"), but you could simply use some constants and put them into a static class, e.g:
public static class MyConstants
{
/// <summary>documentation here</summary>
public const string ValueA = "somevalue";
/// <summary>documentation here</summary>
public const string ValueB = "something else with special characters &#";
// etc.
}
Usage:
var x = MyConstants.ValueB;
One issue you might find with enums and more especially constants is that if you change the source assembly which defines the enum or constant, but don't recompile dependent assemblies, you'll end up mismatching in the source and dependent assemblies. For example:
public const int myConst = 5;
You later change this to:
public const int myConst = 10;
In the source assembly, which was rebuilt, it's 10. But it's 5 in any dependent assemblies that were not rebuilt.
To avoid this, use readonly instead of const. For example:
public readonly int myConst = 5;
This is different than a const, which is more like a C++ #define which causes the value to be placed directly in code. Readonly will cause a lookup at runtime, so if you don't recompile your dependent assemblies you'll still get the correct, updated value.
EDITED: Updated 3/23/09. See rest of post at bottom. I'm still having trouble with the indexer. Anymore help or examples would really help me out.
Write a class, MyCourses, that contains an enumeration of all the
courses that you are currently taking.
This enum should be nested inside of
your class MyCourses. Your class
should also have an array field that
provides a short description (as a
String) of each of your courses. Write
an indexer that takes one of your
enumerated courses as an index and
returns the String description of the
course.
Write a class MyFriends that contains an indexer that provides
access to the names of your friends.
namespace IT274_Unit4Project
{
public class MyCourses
{
// enumeration that contains an enumeration of all the courses that
// student is currently enrolled in
public enum CourseName {IT274= 0,CS210 = 1}
// array field that provides short description for each of classes,
// returns string description of the course
private String[] courseDescription =
{"Intermediate C#: Teaches intermediate elements of C# programming and software design",
"Career Development Strategies: Teaches principles for career progression, resume preparation, and overall self anaylsis"};
// indexer that takes one of the enumerated courses as an index
// and returns the String description of the course
public String this[CourseName index]
{
get
{
if (index == 1)
return courseDescription[0];
else
return courseDescription[1];
}
set
{
if (index == 1)
courseDescription[0] = value;
else
courseDescription[1] = value;
}
}
}
}//end public class MyCourses
I'm working on this homework project and having trouble understanding the text explaining how to correctly take the accessed value of the enumeration and then apply the string array value to it. Can you please help me understand this? The text we are using is very difficult and poorly written for a beginner to understand, so I'm kind of on my own here. I've got the first parts written, but need some help on the accessing of the enumeration value and assigning, i think i'm close, but don't understand how to properly get and set the values on this.
Please do not provide me with direct code answers, unless a MSDN style explanation that is generalized and not specific to my project. ie:
public class MyClass
{ string field1;
string field2;
//properties
public string Value1
get etc...
Thanks!
First of all, the base type of an enumeration has to be a numeric value type, so you can't have an enumeration with base type string. The following isn't going to compile:
public enum CourseName
{
Class1 = "IT274-01AU: Intermediate C#",
Class2 = "CS210-06AU: Career Development Strategies"
}
So change it to use the default base type of int. Something like the following will do, but change the names as you see fit (you might want to use the course name instead of the code, for example). Remember also that you should use meaningful names whenever possible in an enumeration.
public enum Courses
{
IT274_01AU,
CS210_06AU
}
(I know you said you didn't want specific code examples, but I think this one illustrates my point much more clearly than any explanation.)
Second, you're on the right track with the indexer, but you have to think of how to relate the enumeration to the array of string descriptions. Remember, an enumeration is nothing more than a finite set of glorified (named) numbers. With the above Courses enumeration, you have two values named IT274_01AU and CS210_06AU. So in the indexer, you have to map each of these values to the string description. There are multiple ways to do it, but the simplest one would be a switch statement, for example:
switch (myEnum)
{
case value1:
return string1;
case value2:
return string2;
}
Another option, however is to explicitly map the enum values to its base type, and use the base type to index into your array. For example, if you have the enum
public enum Enumerations
{
value1 = 0,
value2 = 1
}
then you can index directly into an array using myArray[(int)myEnum]. This may be of use and is the slightly-more-advanced-but-less-lines-of-code-and-arguably-easier-to-understand method.
(resisting the urge to write code)
First off, an enumeration is a named list of integers and (per MSDN) the approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
Also, remember that courseDescription is an array of strings and the purpose of the indexer is to give you an index into that array (ie. [0] returns the first string, [1] returns the second, etc.).