i am open your ideas: i really dislike this usage . how to convert enum to string via attributes. But please be careful my question StringValueAttribute have more than one constructor also fields. How to develop GetStringValue Extention method via StringValueAttribute ??? Best Regards…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace UsingAttributes
{
static void Main(string[] args)
{
Console.WriteLine(UserType.Login.GetStringValue());
Console.Read();
}
}
public enum UserType : int
{
[StringValueAttribute("xyz", "test")]
Login = 1
}
public class StringValueAttribute : Attribute
{
public string UserName { get; protected set; }
public string PassWord { get; protected set; }
public decimal Something { get; protected set; }
public StringValueAttribute(string Username, string Password,decimal something)
{
UserName = Username;
PassWord = Password;
Something =something;
}
public StringValueAttribute(string Username, string Password)
{
UserName = Username;
PassWord = Password;
}
public StringValueAttribute(string Username)
{
UserName = Username;
}
}
public static class Extentions
{
public static String[] GetStringValue(this Enum value)
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];
// Return the first if there was a match.
PropertyInfo[] pi = attribs[0].GetType().GetProperties();
String[] Vals = new String[pi.Length];
int i = 0;
foreach (PropertyInfo item in pi)
{
// Vals[i] = How to return String[]
}
// i dislike return values one by one : attribs[0].UserName
//return attribs.Length > 0 ? attribs[0].UserName : null; // i have more values
}
}
}
Firstly note that
decimalcannot be used as an attribute argument. You can usedoubleor you can use a string and then convert it to a decimal.Your GetStringValue() should work if you replace
with
If you are using C# 4.0, you don’t need three constructors. You can use optional arguments:
And in older versions of C# you can use the
OptionalAttribute: