How to get the Description Attribute in C#

		[CanBeNull]
		public static String? GetDescription<T>( [CanBeNull] this T e ) where T : IConvertible {
			if ( e is not Enum ) {
				return default( String? );
			}

			var type = e.GetType();

			foreach ( Int32 val in Enum.GetValues( type ) ) {
				if ( val != e.ToInt32( CultureInfo.InvariantCulture ) ) {
					continue;
				}

				var ename = type.GetEnumName( val );

				if ( ename is null ) {
					continue;
				}

				var memInfo = type.GetMember( ename );

				if ( memInfo[0].GetCustomAttributes( typeof( DescriptionAttribute ), false ).FirstOrDefault() is DescriptionAttribute descriptionAttribute ) {
					return descriptionAttribute.Description;
				}
			}

			return default( String? );
		}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s