summaryrefslogtreecommitdiff
path: root/Codemerx/Gestor.Model/Model.Converter/EnumDescriptionTypeConverter.cs
blob: 8524561a57c26ddbaaa07edc758f58e5bf030f41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;

namespace Gestor.Model.Converter
{
	public class EnumDescriptionTypeConverter : EnumConverter
	{
		public EnumDescriptionTypeConverter(Type type) : base(type)
		{
		}

		public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
		{
			if (destinationType != typeof(string))
			{
				return base.ConvertTo(context, culture, value, destinationType);
			}
			if (value == null)
			{
				return string.Empty;
			}
			FieldInfo field = value.GetType().GetField(value.ToString());
			if (field == null)
			{
				return string.Empty;
			}
			DescriptionAttribute[] customAttributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
			if (customAttributes.Length == 0 || string.IsNullOrEmpty(customAttributes[0].Description))
			{
				return value.ToString();
			}
			return customAttributes[0].Description;
		}
	}
}