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, ""},
};
}
Related
This question already has answers here:
Associating enums with strings in C#
(38 answers)
Can enums contain strings? [duplicate]
(6 answers)
Closed 1 year ago.
I know enums can't be strings
I would like a data structure with the utility of an enum, but one which returns strings instead of integers. To be clear, I want the return type to be the enum-like type, not string. Basically, I want to be able to force a property to be usable as a string but is only allowed to be set to a value in a defined set of strings. Something like
stringenum Unit {
Pixels = "px",
Inches = "in"
}
class Settings {
public Unit Unit { get; set; }
}
var settings = new Settings() { Unit = Unit.Pixels };
...
unitLabel.Text = settings.Unit;
I've seen some solutions that just create a class with properties that return a certain string. However, I need the return type to be limited to a set, not just any string.
EDIT FOR CLARIFICATION
Consider my previous example in addition to this method:
public void WriteUnit(Unit unit)
{
Console.WriteLine(unit);
}
// Calling
WriteUnit(Unit.Pixels); // Prints "px"
WriteUnit("px"); // ARGUMENT EXCEPTION
This method will throw an ArgumentException if you pass it a string. It only accepts the type. This is specifically what I'm looking for.
As mentioned in the comments, you cannot directly map an enum to a string.
That said, there is nothing preventing you from creating a map of enum to string values, that can only be accessed via the enum. If you maintain the mapping, you can guarantee that the value always exist.
public enum Unit
{
Pixels,
Inches
}
public static class UnitMapper
{
private static readonly Dictionary<Unit, string> _map
= new Dictionary<UserQuery.Unit, string>()
{
{ Unit.Pixels, "px" },
{ Unit.Inches, "in" }
}
public static string GetUnit(Unit unit)
{
return _map[unit];
}
}
Based on your additional comments, this can be combined with a custom user-defined implicit operator to give you the type of functionality you are looking for, although you will still have to call the overridden .ToString() to output a string.
public struct UnitWrapper
{
private readonly string _unitString;
private readonly Unit _unit;
public UnitWrapper(Unit unit)
{
_unit = unit;
_unitString = UnitMapper.GetUnit(_unit);
}
public static implicit operator UnitWrapper(Unit unit)
{
return new UnitWrapper(unit);
}
public override string ToString() => _unitString;
}
This can then be used as follows:
public class Settings
{
public UnitWrapper UnitWrapper { get; set; }
}
var settings = new Settings { UnitWrapper = Unit.Pixels };
string px = settings.UnitWrapper.ToString();
This question already has answers here:
Return multiple values to a method caller
(28 answers)
Closed 4 years ago.
I have been working with my software using C# in visual studio. But i want to return multiple values in my method, How to return multiple values in a method in C#.... Is it possible??
You can use .NET 4.0+'s Tuple:
For example:
public Tuple<int, int> GetMultipleValue()
{
return Tuple.Create(1,2);
}
it's much easier now
For example:
public (int, int) GetMultipleValue()
{
return (1,2);
}
Do you want to return values of a single type? In that case you can return an array of values. If you want to return different type of values you can create an object, struct or a tuple with specified parameters and then assign those values to these parameters. After you create an object you can return it from a method.
Example with an object:
public class DataContainer
{
public string stringType { get; set; }
public int intType { get; set; }
public bool boolType {get; set}
public DataContainer(string string_type, int int__type, bool bool_type)
{
stringType = string_type;
intType = int__type;
boolType = bool_type;
}
}
Example with a struct:
public struct DataContainer
{
public stringstringType;
public int intType;
public bool boolType;
}
Example with a tuple:
var DataContainer= new Tuple<string, int, bool>(stringValue, intValue, boolValue);
You could create a struct that has multiple variables inside of it.
See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/struct .
Your options are returning a struct, a class, a (named?) tuple or alternatively you can use out parameters
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());
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.
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.