Enums and Attributes
-
I can't for the life of me work out (or find samples on) how to read back the attribute of an entry in an Enum, for example:
Public Enum Colours <Description="Bright Red"> BrightRed = 0 <Description="Brilliant Yellow"> BrightYellow = 1 <Description="Puce"> Horrible = 2 End Enum
I know it has something to do with Reflection, but that doesnt seem to help :confused: Ultimately I want to write a function to able to do something like GetDescription(GetType(Colours)) Thanks, ro. -
I can't for the life of me work out (or find samples on) how to read back the attribute of an entry in an Enum, for example:
Public Enum Colours <Description="Bright Red"> BrightRed = 0 <Description="Brilliant Yellow"> BrightYellow = 1 <Description="Puce"> Horrible = 2 End Enum
I know it has something to do with Reflection, but that doesnt seem to help :confused: Ultimately I want to write a function to able to do something like GetDescription(GetType(Colours)) Thanks, ro.you mean something like this : VB:
Public Enum Colours
BrightRed = 0
BrightYellow = 1
Horrible = 2
End EnumPrivate Sub Button1\_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim c As Colours MessageBox.Show(GetColours(c.BrightRed)) End Sub Public Function GetColours(ByVal i As Integer) As String Dim clr As Colours Select Case i '/// numerical value of the colour. Case clr.BrightRed Return "you chose BrightRed" '/// show the colour you chose. Case clr.BrightYellow Return "you chose BrightYellow" Case clr.Horrible Return "you chose Horrible" End Select End Function
hope that helps a little:)
Private void ExpectingTwins(string twins)
{
switch(twins)
{
Case ("twins on the way"):
MessageBox.Show("for mr and mrs dynamic","twins on the way");
break;
}
}
-
I can't for the life of me work out (or find samples on) how to read back the attribute of an entry in an Enum, for example:
Public Enum Colours <Description="Bright Red"> BrightRed = 0 <Description="Brilliant Yellow"> BrightYellow = 1 <Description="Puce"> Horrible = 2 End Enum
I know it has something to do with Reflection, but that doesnt seem to help :confused: Ultimately I want to write a function to able to do something like GetDescription(GetType(Colours)) Thanks, ro.The following function should work for you ...
Imports System.ComponentModel Imports System.Reflection Private Function GetContentTypeValue(ByVal value As Colours) As String Dim fi As FieldInfo = value.GetType.GetField(value.ToString) Dim attributes As DescriptionAttribute() = CType(fi.GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute()) If attributes.Length > 0 Then Return attributes(0).Value Else Return String.Empty End If End Function