Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define String ENUM in VB.Net

I am using Window Application for my project. There is situation where i need to define string enum and using it in my project.

i.e.

Dim PersonalInfo As String = "Personal Info" Dim Contanct As String = "Personal Contanct"      Public Enum Test         PersonalInfo         Contanct     End Enum 

Now i want value of that variable PersonalInfo and Contract as "Personal Info" and "Personal Contanct".

How can i get this value using ENUM? or anyother way to do it.

Thanks in advance...

like image 466
Brijesh Patel Avatar asked Sep 07 '12 05:09

Brijesh Patel


2 Answers

For non-integer values, Const in a Structure (or Class) can be used instead:

Structure Test     Const PersonalInfo = "Personal Info"     Const Contanct = "Personal Contanct" End Structure 

or in a Module for direct access without the Test. part:

Module Test     Public Const PersonalInfo = "Personal Info"     Public Const Contanct = "Personal Contanct" End Module 

In some cases, the variable name can be used as a value:

Enum Test     Personal_Info     Personal_Contanct End Enum  Dim PersonalInfo As String = Test.Personal_Info.ToString.Replace("_"c, " "c)  ' or in Visual Studio 2015 and newer: Dim Contanct As String = NameOf(Test.Personal_Contanct).Replace("_"c, " "c) 
like image 138
Slai Avatar answered Sep 21 '22 16:09

Slai


You could just create a new type

''' <completionlist cref="Test"/> Class Test      Private Key As String      Public Shared ReadOnly Contact  As Test = New Test("Personal Contanct")     Public Shared ReadOnly PersonalInfo As Test = New Test("Personal Info")      Private Sub New(key as String)         Me.Key = key     End Sub      Public Overrides Function ToString() As String         Return Me.Key     End Function End Class 

and when you use it, it kinda looks like an enum:

Sub Main      DoSomething(Test.Contact)     DoSomething(Test.PersonalInfo)  End Sub  Sub DoSomething(test As Test)     Console.WriteLine(test.ToString()) End Sub 

output:

Personal Contanct
Personal Info

like image 43
sloth Avatar answered Sep 19 '22 16:09

sloth