Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an "enum" type property value dynamically

I need to create a property in a class that will give the programmer a list of values to choose from. I have done this in the past using the enums type.

Public Enum FileType
    Sales
    SalesOldType
End Enum

Public Property ServiceID() As enFileType
    Get
        Return m_enFileType
    End Get
    Set(ByVal value As enenFileType)
        m_enFileType = value
    End Set
End Property

The problem is I would like to populate the list of values on init of the class based on SQL table values. From what I have read it is not possible to create the enums on the fly since they are basically constants.

Is there a way I can accomplish my goal possibly using list or dictionary types? OR any other method that may work.

like image 520
Dan Rowe Avatar asked Jul 21 '26 11:07

Dan Rowe


1 Answers

I don't know if this will answer your question, but its just my opinion on the matter. I like enums, mostly because they are convenient for me, the programmer. This is just because when I am writing code, using and enum over a constant value gives me not only auto-complete when typing, but also the the compile time error checking that makes sure I can only give valid enum values. However, enums just don't work for run-time defined values, since, like you say, there are compile time defined constants.

Typically, when I use flexible values that are load from an SQL Table like in your example, I'll just use string values. So I would just store Sales and SalesOldType in the table and use them for the value of FileType. I usually use strings and not integers, just because strings are human readable if I'm looking at data tables while debugging something.

Now, you can do a bit of a hybrid, allowing the values to be stored and come from the table, but defining commonly used values as constants in code, sorta like this:

 Public Class FileTypeConstants
       public const Sales = "Sales"
       public const SalesOldType = "SalesOldType"
 End Class

That way you can make sure when coding with common values, a small string typo in one spot doesn't cause a bug in your program.

Also, as a side note, I write code for and application that is deployed internally to our company via click-once deployment, so for seldom added values, I will still use an enum because its extremely easy to add a value and push out an update. So the question of using and enum versus database values can be one of how easy it is to get updates to your users. If you seldom update, database values are probably best, if you update often and the updates are not done by users, then enums can still work just as well.

Hope some of that helps you!

like image 152
Kratz Avatar answered Jul 24 '26 06:07

Kratz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!