I'm always confused which kind of enumeration I should use. A hashtable, an enum, a struct a dictionary, an array (how oldschool), static strings...
Instead of using strings in my code I want to use a beautiful enum like so:
public enum MyConfigs
{
Configuration1,
Configuration2
}
Problem is that I don't always want to convert my enum toString() as I'm not interested in the index representation of the enum.
What is the best way to represent a public enumeration of string based values?
In the end I would love to end up with using MyConfigs.Configuration1 where needed in my code.
I prefer defining "grouped" constants as static members of a dummy static class, like so:
public static class FieldNames
{
public const string BRANCH_CODE = "_frsBranchCode";
public const string BATCH_ID = "_frsBatchId";
public const string OFFICE_TYPE = "_frsOfficeType";
}
But of course they are not "enumerable" directly, so you can't foreach over them unless you provide a static array too:
public static string[] AllFieldNames
{
get
{
return new string[]
{
FieldNames.BRANCH_CODE,
FieldNames.BATCH_ID,
FieldNames.OFFICE_TYPE
};
}
}
public static class MyConfigs
{
public const string Configuration1 = "foo",
Configuration2 = "bar"
}
This is then pretty-much identical to how enums are implemented (ignoring the whole "it must be an integer" thing).
Type-safe enum pattern?
public class StringEnum
{
#region Enum Values
public static readonly StringEnum ValueOne = new StringEnum("Value One");
public static readonly StringEnum ValueTwo = new StringEnum("Value Two");
#endregion
#region Enum Functionality
public readonly string Value;
private StringEnum(string value)
{
Value = value;
}
public override string ToString()
{
return value;
}
#endregion
}
You can use this like:
private void Foo(StringEnum enumVal)
{
return "String value: " + enumVal;
}
If you never need to pass these values around in a type-safe manner to methods etc. then it is probably best to just stick with a constants file.
Related
I am trying to compare values that I am getting from web service, but sometimes I get int value, sometimes i get string. So it would be great that i could only check for Type.value1.
for example:
enum Type { value1 = 1 , value1="one"}
and like that for more value2, etc...
But of course, I cannot do this because it I cannot add two definitons for value1.
Sometimes a type that behaves mostly like an enum but has some richer behaviour can be very useful:
public sealed class MyFakeEnum {
private MyFakeEnum(int value, string description) {
Value = value;
Description = description;
}
public int Value { get; private set; }
public string Description { get; private set; }
// Probably add equality and GetHashCode implementations too.
public readonly static MyFakeEnum Value1 = new MyFakeEnum(1, "value1");
public readonly static MyFakeEnum Value2 = new MyFakeEnum(2, "value2");
}
You can consider adding attributes to the enums and use reflection.
enum Type
{
[Description("One")]
value1 = 1
}
I also make use of using decorating the enum with a description attribute as described by BSoD_ZA. But I would suggest that you then implement an extension method for the enumeration to obtain the string description for example:
public static class EnumExtension
{
public static string ToDescription<TEnum>(this TEnum enumValue) where TEnum : struct
{
return ReflectionService.GetClassAttribute<DescriptionAttribute>(enumValue);
}
}
enum Type
{
[Description("One")]
value1 = 1
}
var value = Type.Value1;
Console.Writeline(value.ToDescription());
The guidelines are clear for enumerations...
Do use a singular name for an enumeration, unless its values are bit fields.
(Source: http://msdn.microsoft.com/en-us/library/ms229040.aspx)
...but not so clear for a class of constants (or read-only static fields/propertes). For example, should the name of this class be singular or plural?
public static class Token // or Tokens?
{
public const string Foo = "Foo";
public const string Bar = "Bar";
public const string Doo = "Doo";
public const string Hicky = "Hicky";
}
I would use the plural: Tokens. This implies that the static class is serving as a collection of items of some sort (whose runtime types are not that of the class).
On the other hand, an enumeration's fields are instances of the enumeration type. For example, TypeCode.String is a TypeCode. It would be weird to say that TypeCodes.String is a TypeCodes.
However, in your Tokens example, using the singular gives us Token.Foo, which is a token, but it is not a Token (it is a string).
(Or, if you use the plural class name, Tokens.Foo is a string, not a Tokens. Ack!)
Since both are used essentially the same way, and are conceptually the same thing, I'd recommend just following the enum guidelines.
I don't have any official naming standard to link to, but I can tell you what I would do.
I would use the plural name: Tokens
I would use the plural name: Tokens
However you may consider creating a Token class for holding the const value.
This would be similar to System.Windows.Media.Colors where e.g. Colors.Blue returns a System.Windows.Media.Color instance.
public class Token
{
public Token(string value)
{
Value = value;
}
public string Value { get; private set; }
public static implicit operator string(Token token)
{
return token == null ? null : token.Value;
}
public bool Equals(string value)
{
return String.Equals(Value, value);
}
public override bool Equals(object obj)
{
var other = obj as Token;
if (other == null)
{
return false;
}
return Equals(other.Value);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override string ToString()
{
return Value;
}
}
public static class Tokens
{
public static readonly Token Foo = new Token("Foo");
}
class Program
{
static void Main(string[] args)
{
// You can use it as if they were string constants.
string token = Tokens.Foo;
bool areEquals = String.Equals(token, Tokens.Foo);
}
}
I have a field which is static and readonly. The requirement is that the value should be allocated to the field at the login time and after that it should be readonly. How can i achieve this ?
public static class Constant
{
public static readonly string name;
}
Kindly guide.
If you declare a readonly field you can only set it in the constructor of the class. What you could do is implementing a property only having a getter and exposing a change method that is used during your logon sequence to modify the value. Other Parts of your program can use the property effectivly not allowing them to change the value.
public static class Constant
{
public static string Name
{
get
{
return name;
}
set
{
if (name == null)
name = value;
else
throw new Exception("...");
}
}
private static string name;
}
you need a static constructor
public static class Constant
{
public static readonly string name;
static Constant()
{
name = "abc";
}
}
Just assign the value in the declaration (or constructor) like this:
public static class Constant
{
public static readonly string name = "MyName";
}
readonly is sugar for the compiler, telling him, that you don't intend to change the value outside the constructor. If you do so, he will generate an error.
You can also create a static constructor in your static class
static Constant()
{
name = "Name";
}
Hi Is there a way to declare an enum or to customize the way of declaring an enum which returns an object in C#?
private enum testEnum
{
firstname =1
,lastname = 2
}
and if we want to return the names rather than 1 and 2 ?
like testEnum.firstname returns 1 .
I want to declare an enum to return objects like in Java . is it possible?
You can do this:
public class NameEnum
{
static NameEnum()
{
FirstName = new NameEnum("FirstName");
LastName = new NameEnum("LastName");
}
public static NameEnum FirstName { get; private set; }
public static NameEnum LastName { get; private set; }
private NameEnum(string name)
{
this.Name = name;
}
public string Name { get; private set; }
}
Is that close enough?
http://msdn.microsoft.com/de-de/library/system.enum.aspx
An enumeration is a set of named constants whose underlying type is any integral type except Char. If no underlying type is explicitly declared, Int32 is used. Enum is the base class for all enumerations in the .NET Framework.
You can use interfaces for this:
interface IColorEnum {};
class ColorEnum: IColorEnum
{
public static const Red = new ColorEnum();
public static const Green = new ColorEnum();
public static const Blue = new ColorEnum();
};
And use it like usual:
void foo(IColorEnum color)
{
if(color == ColorEnum.Red) {...}
}
Update+improve: you can even drop interface and just use class with couple of public static fields with type of this class and private constructor to prevent creating new instances of it:
class ColorEnum
{
private ColorEnum() {};
public static const Red = new ColorEnum();
public static const Green = new ColorEnum();
public static const Blue = new ColorEnum();
};
The docs state:
Every enumeration type has an underlying type, which can be any integral type except char.
Assuming you mean object to be complex/reference type. then the answer to your question is no. You could always create a class with named properties containing reference types.
I guess that you be a class exposing static fields that can then be of any type you want.
I think this is only possible in java.
It seems that you want to implement singleton the Joshua Bloch way.
This question already has answers here:
Associating enums with strings in C#
(38 answers)
Closed 9 years ago.
How can I declare an enum that has strings for values?
private enum breakout {
page = "String1",
column = "String2",
pagenames = "String3",
row = "String4"
}
No they cannot. They are limited to numeric values of the underlying enum type.
You can however get similar behavior via a helper method
public static string GetStringVersion(breakout value) {
switch (value) {
case breakout.page: return "String1";
case breakout.column: return "String2";
case breakout.pagenames: return "String3";
case breakout.row: return "String4";
default: return "Bad enum value";
}
}
As others have said, no you cannot.
You can do static classes like so:
internal static class Breakout {
public static readonly string page="String1";
public static readonly string column="String2";
public static readonly string pagenames="String3";
public static readonly string row="String4";
// Or you could initialize in static constructor
static Breakout() {
//row = string.Format("String{0}", 4);
}
}
Or
internal static class Breakout {
public const string page="String1";
public const string column="String2";
public const string pagenames="String3";
public const string row="String4";
}
Using readonly, you can actually assign the value in a static constructor. When using const, it must be a fixed string.
Or assign a DescriptionAttribute to enum values, like here.
No, but you can get the enum's value as a string:
Enum.ToString Method
private enum Breakout {
page,
column,
pagenames,
row
}
Breakout b = Breakout.page;
String s = b.ToString(); // "page"
An enum has integer as underlying type by default, which is also stated here on msdn.
Maybe Enum.GetName()/Enum.GetNames() can be helpful for you.
You can create a dictionary of enums.
public enum OrderType
{
ASC,
DESC
}
public class MyClass
{
private Dictionary<OrderType, string> MyDictionary= new Dictionary<OrderType, string>()
{
{OrderType.ASC, ""},
{OrderType.DESC, ""},
};
}