For example:
(1).SomeFunction().Equals("one")
(2).SomeFunction().Equals("two")
I really only need it for digits 1-9 in the case I'm working with, should I just use a switch/select case?
Update I won't need localization in this case either.
Update 2 Here's what I ended up using:
Private Enum EnglishDigit As Integer
zero
one
two
three
four
five
six
seven
eight
nine
End Enum
(CType(someIntThatIsLessThanTen, EnglishDigit)).ToString()
How about an enumeration?
enum Number
{
One = 1, // default value for first enum element is 0, so we set = 1 here
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
}
Then you can type things like...
((Number)1).ToString()
If you need localization then you can add a DescriptionAttribute
to each enum value. The attribute's Description
property would store the name of the resourse item's key.
enum Number
{
[Description("NumberName_1")]
One = 1, // default value for first enum element is 0, so we set = 1 here
[Description("NumberName_2")]
Two,
// and so on...
}
The following function will grab the value of the Description
property from the attribute
public static string GetDescription(object value)
{
DescriptionAttribute[] attributes = null;
System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString());
if (fi != null)
{
attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
}
string description = null;
if ((attributes != null) && (attributes.Length > 0))
{
description = attributes[0].Description;
}
return description;
}
This can be called in the following manner:
GetDescription(((Number)1))
From that you can then pull the relevant value from the resource file, or just call .ToString()
if null
was returned.
Various commenters have pointed out (and I have to agree) that it would be simpler to just use the enum value names to reference localised strings.
create a dictionary of strings:
string[] digits = new string[]
{
"zero",
"one",
"two",
...
};
string word = digits[digit];
Use a lookup table; an array will do. It's no slower than an enum, and it's easier to localize.
edit
Andrey's code sample is what I was suggesting, although I think calling it a dictionary is a bit confusing.
If you don't need localization, I'd suggest Richard Ev's solution. For localization, however, I'd suggest adding the ten digit names to a resource file, for example NumberName_0
to NumberName_9
. This way, when looking up a number, you can just load the resource with the name String.Format("NumberName_{0}", mydigit)
.
The same technique, by the way, also works fine for localizable enumeration names or descriptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With